Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 41 ยท Drawing and Images

Text and Fonts in Pygame

Render text in Pygame with Font and SysFont, blit and center it, measure widths for layout, wrap long paragraphs, cache rendered text and show scores and FPS counters.

Scores, menus, dialogue, labels: nearly every game shows text. Pygame has no "draw text" function. Instead you use pygame.font to render text into a new Surface and then blit that surface like any image. This lesson shows the whole workflow: creating fonts, rendering and positioning text, measuring it for layout, wrapping paragraphs and doing it efficiently.

The three steps

Python
pygame.font.init()                                  # or pygame.init()
font = pygame.font.Font(None, 48)                   # 1. create a font
label = font.render("Score: 120", True, (255, 255, 255))   # 2. render to a Surface
screen.blit(label, (20, 20))                        # 3. blit it

font.render(text, antialias, color, background=None) returns a Surface just big enough for the text. Pass True for antialias to get smooth edges (almost always what you want; use False for crisp pixel fonts). With no background the surface is transparent around the glyphs.

Choosing a font

Constructor Use
pygame.font.Font(None, size) Pygame's built-in default font, always available and identical everywhere
pygame.font.Font("assets/font.ttf", size) A font file you ship with the game (best for a consistent look)
pygame.font.SysFont("arial", size, bold, italic) A font installed on the player's computer; may be missing or differ per system

size is the font height in pixels. For a game you plan to share, ship a .ttf or .otf file in your assets folder; SysFont falls back silently to the default when a name is missing. pygame.font.get_fonts() lists system fonts, and font.set_bold(True), set_italic and set_underline change the style.

Try it: render and measure

A rendered text surface is an ordinary Surface, so you can ask it for its size and rect. This is how you center text or place it relative to something else.

Python Render text and read its size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

font.size(text) returns the pixel size without creating a surface, which is the cheap way to measure.

Positioning

Use get_rect() with an anchor, just as for any surface:

Python
title = big_font.render("SPACE DODGER", True, WHITE)
screen.blit(title, title.get_rect(midtop=(screen.get_width() // 2, 40)))

score = font.render(f"Score: {score_value}", True, WHITE)
screen.blit(score, score.get_rect(topright=(screen.get_width() - 20, 15)))

Anchors such as center, midtop and topright mean the text stays correctly aligned even when its width changes.

Multi-line text and word wrap

render draws a single line; a "\n" in the string is handled as a line break only in newer versions. Pygame-ce lets you pass wraplength (in pixels) so long text breaks automatically:

Python
paragraph = font.render(long_text, True, WHITE, wraplength=400)

When you need control (different colors per line, or portability to old pygame), wrap the words yourself with font.size() to measure each candidate line, then render and blit line by line using font.get_linesize() for spacing.

Python Word wrap with font.size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real game you would render each line returned by wrap() and blit them at increasing y positions, stepping by font.get_linesize().

Showing changing values

Scores, timers and FPS counters change. The obvious approach renders them every frame:

Python
label = font.render(f"FPS: {clock.get_fps():.0f}", True, WHITE)
screen.blit(label, (10, 10))

This is fine for a few labels. Rendering is comparatively slow, though, so for lots of text, cache surfaces and re-render only when the text changes:

Python
class Label:
    def __init__(self, font, color):
        self.font, self.color = font, color
        self.text, self.surface = None, None

    def draw(self, screen, text, pos):
        if text != self.text:                # re-render only on change
            self.text = text
            self.surface = self.font.render(text, True, self.color)
        screen.blit(self.surface, pos)

Try it: a cached label

This checks the caching logic by counting how many times the expensive render actually runs while the score stays the same for most frames.

Python Render only when the text changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three hundred frames needed only six renders. For text that updates every frame (like a timer with decimals) cache is no help, but the cost is still small for a few labels.

Text effects

  • Shadow: render the text twice, first in dark gray offset by (2, 2), then in white at the real position.
  • Outline: render the outline color at the eight surrounding offsets, then the main text on top.
  • Fade: surface.set_alpha(value) on the label.
  • Typewriter: blit a growing slice of the string, one more character every 40 ms.
  • Pixel fonts: turn antialias off and use a bitmap-style font at its native size.

Common mistakes

  • Creating a Font inside the loop every frame: it is slow. Create fonts once.
  • Calling render before pygame.font.init() or pygame.init().
  • Rendering an empty string with some fonts: you get a zero-width surface; guard with if text.
  • Passing a color with four components when no background is given: it is fine, but alpha in the color is not used for the text.
  • Depending on SysFont("arial"): another computer may not have it. Bundle a font file.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does font.render("Hi", True, WHITE) return?

    Rendering creates a new Surface that you then blit to the screen like any image.
  2. 2. What does the second argument of font.render control?

    True renders smooth text; False renders hard-edged pixels.
  3. 3. Which is the best way to make your game look the same on every computer?

    System fonts differ between machines. A bundled file is always the same.
  4. 4. How do you measure text width without rendering it?

    font.size(text) returns (width, height) in pixels and is cheap.
  5. 5. Why cache rendered text surfaces?

    Re-render only when the text changes and reuse the surface otherwise.

Summary

  • Render text with font.render(text, antialias, color) to get a Surface, then blit it.
  • Use Font(None, size) or a bundled .ttf; SysFont depends on the player's system.
  • font.size() measures; get_rect(center=...) aligns.
  • Wrap long text with wraplength or your own function.
  • Create fonts once and cache labels that rarely change.

Next: Images and Transforms