Working With Text In Pygame

Creating A Helper Function

Pygame doesn’t have built in functionality for drawing text, this is something we have to add in ourselves. We begin by taking text in the form of a string, then we render that text into an image using the font module and lastly we draw (or blit) the image on the screen

All of this can be achieved by creating out own helper function:

				
					def draw_text(text, font, text_col, x, y):
  img = font.render(text, True, text_col)
  screen.blit(img, (x, y))
				
			

The function needs a few arguments passed into it, these are the text, the font, colour and position on the screen as x & y coordinates.

Before we can use this function, we need to define a font using pygame’s font module.

				
					text_font = pygame.font.SysFont("Helvetica", 30)
				
			

I will come back to this font module and talk about the various functions within it, but for now let’s see if we can blit this text on the screen.

				
					import pygame

pygame.init()

SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

text_font = pygame.font.SysFont("Helvetica", 30)

#function for outputting text onto the screen
def draw_text(text, font, text_col, x, y):
  img = font.render(text, True, text_col)
  screen.blit(img, (x, y))

run = True
while run:

  screen.fill((255, 255, 255))

  draw_text("Hello World", text_font, (0, 0, 0), 220, 150)

  for event in pygame.event.get():
   if event.type == pygame.QUIT:
      run = False

  pygame.display.flip()

pygame.quit()
				
			

And there you have it, a working text function… but there is still a lot more functionality we can add to this so let’s take a deeper look at the font module.

Font Modifiers

When creating the font object, I picked a system font, but pygame comes with its own default font. To load that we pass None into the font object.

				
					text_font = pygame.font.SysFont("Helvetica", 30)
				
			

Font has a couple of flags that by default are set to False. These are bold and italic. You can apply them to your font by setting these flags to True when defining the font.

				
					text_font = pygame.font.SysFont("Helvetica", 30, bold=True, italic=True)
				
			

What if you want to use a custom font instead? This can be loaded in a similar way but instead of calling SysFont, we call Font and pass in a font filename.

Note: For this to work, you need to download a font file for the specific font you want to use.

				
					text_font = pygame.font.Font("turok.ttf", 30)
				
			

Related Posts

One thought on “Working With Text In Pygame

Leave a Reply

Your email address will not be published. Required fields are marked *