There are two steps to displaying text within a Pygame Python program:
- Create the font variable
- Convert the text to an image that is then drawn on the screen
The following walks you through the two steps with the program we have been creating over the last few pages.
- Create the font variable. Create a font variable before your game loop. Typically I would add it just after all the colours are defined.
ARIAL = pygame.font.SysFont("Arial", 60)
- Convert the text to an image and draw it to screen. Inside your loop, before the
pygame.display.update(), add two lines to render your text to a bitmap, and then blit that bitmap to the screen window.
label = ARIAL.render("Hello Python!", 1, (255,255,255)) window.blit(label, (300, 50))
The (300,50) in the
window.blit command is the coordinates of where to draw the text.
The output should look like:
Common mistake: Trying to display numbers
Rendering text is not as friendly as the old
print() command you are used to. Everything must be a string. So, for example, if you have an integer variable called
score that you want to be displaying on screen, remember to convert it to a string first using