leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python Pygame font creation

Estimated reading: 2 minutes 15 views

Not only can we draw shapes on the screen, but we can also draw text to the screen. Pygame provides some very simple to use functions for creating fonts and text. Font (font) is a description of a font type, representing a set of letters, numbers, symbols and characters drawn in a uniform style, such as SimHei and Times New Roman are fonts.

We can call the “pygame.font.SysFont()” function to create a Font object, this function has two parameters, the first parameter is the font name, and the second parameter is the font size (in points). Take a look at a program, the code is as follows.

import pygame
pygame.init()
windowSurface=pygame.display.set_mode((800,600))
WHITE=(255,255,255)
myString="Hello World!"
font = pygame.font.SysFont("Times New Roman", 48)
text = font.render(myString, True, WHITE)
Running=True
while Running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Running=False
    windowSurface.blit(text, (200,250))
    pygame.display.update()
pygame.quit()

The highlighted code in this code is newly added, the others we have seen before. Here a constant called WHITE is defined and the tuple (255, 255, 255) is copied to it, which represents white. Then, define a string variable called myString that contains the text you want to draw on the screen to display to the user, in this example, “Hello World!”.

Then call pygame.font.SysFont to create the Font object and assign it to a variable named font, this function call allows us to draw to the Pygame Surface in 48-point Times New Roman font.

Next, we use the render() command on the created font object to draw the string onto a single Surface. In the line of code text = font.render(myString, True, WHITE), render()’s

  • The first parameter is a string of text to be drawn;
  • The second parameter specifies whether you want to antialias a Boolean value, if it is True, the text looks smoother;
  • The third parameter is the color used to render the text, in this example white is used.

Assign this Font object to the variable text. Then in the game loop, call the blit() function to copy the pixels from one Surface to the other. windowSurface.blit(text, (200,250)) is to copy the text object to the surface of screen.

Run the code, you can see “Hello World!” is displayed in the window, as shown in the following figure.

Python Pygame font creation

Leave a Comment

CONTENTS