pygame.font

Render text into Surfaces using the built-in font, a font file shipped with your game, or a system font, and measure text for layout.

2 min readUpdated
On this page

Overview#

Text in Pygame is a two-step process: a Font object renders a string into a new Surface, and you blit that Surface where you want it. pygame.init() initialises the font module.

Syntax#

Python
font = pygame.font.Font(None, 36)                   # built-in default font
font = pygame.font.Font("assets/Inter.ttf", 24)    # a font file you ship
font = pygame.font.SysFont("arial", 24, bold=False, italic=False)
text_surface = font.render(text, antialias, color, background=None)
width, height = font.size(text)

Parameters#

ParameterMeaning
file (Font)Path to a TTF/OTF file, or None for Pygame's bundled default font.
sizeHeight in pixels (approximately).
name (SysFont)A system font name, or a comma-separated list of names to try in order.
text (render)The string to draw. Newlines are not handled by render in the original pygame.
antialiasTrue for smooth edges.
color, backgroundText colour, and an optional solid background (no background means transparent).

Return values#

render() returns a new Surface just big enough for the text. size() returns (width, height) without rendering. get_linesize() returns the recommended distance between lines; get_height(), get_ascent() and get_descent() give finer metrics.

Practical example#

font_example.pyDownload
"""pygame.font: default and system fonts, rendering, measuring text and caching rendered text."""
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()

default = pygame.font.Font(None, 40)                        # built-in font, no file needed
mono = pygame.font.SysFont("dejavusansmono,consolas,menlo,monospace", 22)   # first match wins
bold = pygame.font.Font(None, 32)
bold.set_bold(True)

title = default.render("Pygame fonts", True, "gold")        # render once, blit many times
w, h = mono.size("Measured text")                           # size before rendering
print("Text size:", w, h, "line height:", mono.get_linesize())

score_cache = {}


def score_surface(value):
    """Re-render only when the value changes: rendering text is slow."""
    if value not in score_cache:
        score_cache.clear()
        score_cache[value] = bold.render(f"Score: {value}", True, "white")
    return score_cache[value]


score = 0
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            score += 10
    screen.fill((20, 26, 46))
    screen.blit(title, title.get_rect(midtop=(320, 20)))
    screen.blit(mono.render("Measured text", True, "lightblue", (40, 60, 100)), (40, 100))  # with background
    pygame.draw.rect(screen, "white", (40, 100, w, h), 1)
    screen.blit(score_surface(score), (40, 160))
    lines = ["Multi-line text: render each line", "and step down by get_linesize()."]
    for i, line in enumerate(lines):
        screen.blit(mono.render(line, True, "white"), (40, 220 + i * mono.get_linesize()))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Tips#

  • Ship your font. System fonts differ between computers; a TTF file in your game folder looks the same everywhere. Check its license allows bundling. Many open fonts use the SIL Open Font License.
  • Cache rendered text that doesn't change every frame. Rendering is much slower than blitting.
  • Multi-line text: render each line and step down by get_linesize().
  • Styles: set_bold(), set_italic(), set_underline() and set_strikethrough() change the font object.
  • Advanced text: pygame.freetype offers rotation, sizes per call and finer control.

Common errors#

  • pygame.error: font not initialized: call pygame.init() (or pygame.font.init()) first.
  • FileNotFoundError for a font file: build the path from Path(__file__).parent, as with images.
  • Boxes instead of characters: the font doesn't contain those glyphs (common with emoji and some scripts). Use a font that supports them.
  • Text looks blurry when scaled: render at the final size instead of scaling the Surface.

pygame-ce notes#

In pygame-ce, Font.render() takes an extra wraplength argument that wraps text to a pixel width and honours newlines, and Font.align controls alignment of wrapped text. The original pygame lacks both, so code using them needs pygame-ce.

Official documentation#

↑ ↓ to moveEnter to openEsc to close