Build a text input box in Pygame
Let players type their name for a high score table. Pygame's TEXTINPUT events handle Shift, keyboard layouts and accented characters for you; here's a reusable box built on them.
Why not use KEYDOWN?#
KEYDOWN tells you which key was pressed, not which character the player meant. Turning keys into text yourself means handling Shift, Caps Lock, different keyboard layouts and accented characters, and you'd still get it wrong for many players. Pygame 2 provides TEXTINPUT events whose text attribute contains the characters typed, already processed by the operating system.
Use TEXTINPUT for characters and KEYDOWN only for editing keys such as Backspace, Enter and Escape.
The complete box#
"""A reusable text input box using TEXTINPUT events (handles Shift, keyboard layouts and accents)."""
import pygame
class TextBox:
def __init__(self, rect, font, max_length=20, placeholder="Type your name"):
self.rect = pygame.Rect(rect)
self.font = font
self.max_length = max_length
self.placeholder = placeholder
self.text = ""
self.active = False
self.blink = 0.0
def handle(self, event):
"""Returns the text when Enter is pressed, otherwise None."""
if event.type == pygame.MOUSEBUTTONDOWN:
self.set_active(self.rect.collidepoint(event.pos))
elif self.active and event.type == pygame.TEXTINPUT:
if len(self.text) + len(event.text) <= self.max_length:
self.text += event.text # printable characters arrive here
elif self.active and event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
self.text = self.text[:-1]
elif event.key in (pygame.K_RETURN, pygame.K_KP_ENTER):
return self.text.strip()
elif event.key == pygame.K_ESCAPE:
self.set_active(False)
return None
def set_active(self, value):
self.active = value
if value:
pygame.key.start_text_input()
pygame.key.set_text_input_rect(self.rect) # where an on-screen keyboard/IME should appear
else:
pygame.key.stop_text_input()
def update(self, dt):
self.blink = (self.blink + dt) % 1.0
def draw(self, surface):
pygame.draw.rect(surface, (255, 255, 255), self.rect, border_radius=6)
pygame.draw.rect(surface, (36, 87, 166) if self.active else (150, 160, 180), self.rect, 2, border_radius=6)
shown = self.text or self.placeholder
color = (21, 35, 63) if self.text else (150, 160, 180)
label = self.font.render(shown, True, color)
surface.blit(label, (self.rect.x + 10, self.rect.centery - label.get_height() // 2))
if self.active and self.blink < 0.5: # blinking cursor
x = self.rect.x + 10 + (self.font.size(self.text)[0] if self.text else 0)
pygame.draw.line(surface, (21, 35, 63), (x + 1, self.rect.y + 8), (x + 1, self.rect.bottom - 8), 2)
pygame.init()
screen = pygame.display.set_mode((640, 300))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
box = TextBox((120, 110, 400, 50), font)
box.set_active(True)
greeting = ""
running = True
while running:
dt = clock.tick(60) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
result = box.handle(event)
if result:
greeting = f"Hello, {result}!"
box.text = ""
box.update(dt)
screen.fill((20, 26, 46))
box.draw(screen)
screen.blit(font.render(greeting or "Press Enter to submit", True, (244, 197, 49)), (120, 190))
pygame.display.flip()
pygame.quit()How it works#
- Focus: clicking inside the box activates it; clicking elsewhere deactivates it. Only the active box responds to typing.
pygame.key.start_text_input()andstop_text_input()turn text input on and off. On devices with on-screen keyboards, starting text input can show the keyboard, andset_text_input_rect()tells the system where the text field is so input-method windows appear nearby.- Length limit: characters are added only while the text stays within
max_length. - Cursor: a line blinks after the last character, positioned using
font.size(text). - Submitting:
handle()returns the text when Enter is pressed, so the caller decides what to do with it.
Extending it#
- Allowed characters: filter
event.text, for exampleif event.text.isalnum()for names. - Cursor movement: store a cursor index and handle Left, Right, Home and End in
KEYDOWN; insert text at the index instead of appending. - Holding Backspace: enable key repeat with
pygame.key.set_repeat(400, 40)while the box is active. - Several fields: keep a list of boxes and move focus with Tab.
- Input methods (IME) for languages such as Japanese send
TEXTEDITINGevents with text that isn't confirmed yet; draw it underlined after your text if you want to show it.
Fonts and characters#
The default Pygame font covers basic Latin characters. If players will type other scripts, ship a font that contains them (font reference).