How to display text in pygame?
Categories:
Mastering Text Display in Pygame: A Comprehensive Guide

Learn how to effectively render, position, and update text in your Pygame applications, from basic labels to dynamic score displays.
Displaying text is a fundamental requirement for almost any interactive application, and Pygame is no exception. Whether you need to show scores, instructions, menu options, or debug information, Pygame provides robust tools to render text onto your game window. This article will guide you through the process, covering font initialization, text rendering, positioning, and dynamic updates.
The Basics: Initializing Fonts and Rendering Text
Before you can display any text, Pygame needs to initialize its font module and load a font. Pygame can use system fonts or custom font files (like .ttf
or .otf
). Once a font is loaded, you can render text onto a Surface
object, which can then be blitted onto your main display surface.
import pygame
pygame.init()
# Set up the display
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame Text Display")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# 1. Initialize the font module (if not already done by pygame.init())
pygame.font.init()
# 2. Load a font
# Use a system font (e.g., 'arial') or a custom .ttf file
try:
font = pygame.font.SysFont('arial', 48) # Font name, size
except:
# Fallback if 'arial' is not found, or use a default Pygame font
font = pygame.font.Font(None, 48) # Default font, size
# 3. Render the text onto a new Surface
# render(text, antialias, color, background=None)
text_surface = font.render("Hello Pygame!", True, WHITE)
# Get the rectangle of the text surface for positioning
text_rect = text_surface.get_rect()
# Position the text (e.g., center of the screen)
text_rect.center = (WIDTH // 2, HEIGHT // 2)
# Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Drawing
SCREEN.fill(BLACK) # Fill background
SCREEN.blit(text_surface, text_rect) # Blit text surface onto screen
# Update the display
pygame.display.flip()
pygame.quit()
Basic Pygame text rendering example.
pygame.font.init()
before using any font functions. While pygame.init()
often initializes all modules, explicitly calling pygame.font.init()
ensures the font module is ready, especially if you're initializing modules individually.Understanding Text Rendering Workflow
The process of displaying text in Pygame can be broken down into a few distinct steps. Understanding this workflow is crucial for efficient text management, especially when dealing with dynamic text or multiple text elements.
flowchart TD A[Start Pygame] --> B{Initialize Font Module} B --> C[Load Font (SysFont or Font file)] C --> D{Create Text Surface (font.render())} D --> E[Get Text Rectangle (text_surface.get_rect())] E --> F[Position Text Rectangle] F --> G[Blit Text Surface to Display] G --> H[Update Display] H --> I{Game Loop Continues?} I -- Yes --> D I -- No --> J[Quit Pygame]
Pygame Text Rendering Workflow
Dynamic Text and Performance Considerations
For elements like scores, timers, or user input, text needs to change frequently. Re-rendering text every frame can be computationally expensive, especially for complex fonts or large amounts of text. It's best practice to only re-render the text_surface
when the text content actually changes.
import pygame
pygame.init()
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Dynamic Score")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
pygame.font.init()
font = pygame.font.SysFont('arial', 36)
score = 0
last_score = -1 # Use to track if score changed
score_text_surface = None
score_text_rect = None
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
score += 10
# Only re-render if the score has changed
if score != last_score:
score_text_surface = font.render(f"Score: {score}", True, WHITE)
score_text_rect = score_text_surface.get_rect()
score_text_rect.topleft = (10, 10) # Position at top-left
last_score = score
SCREEN.fill(BLACK)
if score_text_surface and score_text_rect:
SCREEN.blit(score_text_surface, score_text_rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Example of dynamic text rendering for a score.
font.render()
method returns a new Surface
object each time it's called. If you're rendering the same text repeatedly without changes, it's more efficient to render it once and store the Surface
and its Rect
.