Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a text input box with Pygame?
Pygame is a free and open-source library for developing multimedia applications like video games using Python. It includes graphics and sound libraries built on top of the Simple DirectMedia Layer (SDL), providing platform-independent interfaces for graphics, sound, and input handling across Windows, Mac OS, and Linux.
Creating text input boxes is essential for games that need user input like player names, chat systems, or configuration settings. This tutorial shows how to build interactive text input boxes using Pygame's event handling and rendering capabilities.
Basic Text Input Box
This example creates a clickable text input box that changes color when active and allows typing with backspace support ?
import pygame
import sys
# Initialize Pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption('Text Input Box')
# Input box variables
user_text = ''
font = pygame.font.SysFont('arial', 32)
input_rect = pygame.Rect(180, 230, 140, 40)
active = False
# Colors
color_active = pygame.Color('lightblue')
color_inactive = pygame.Color('gray')
color = color_inactive
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Check if input box is clicked
if event.type == pygame.MOUSEBUTTONDOWN:
if input_rect.collidepoint(event.pos):
active = True
else:
active = False
# Handle typing when box is active
if event.type == pygame.KEYDOWN and active:
if event.key == pygame.K_BACKSPACE:
user_text = user_text[:-1]
else:
user_text += event.unicode
# Set color based on active state
color = color_active if active else color_inactive
# Fill screen and draw input box
screen.fill('darkblue')
pygame.draw.rect(screen, color, input_rect, 2)
# Render and display text
text_surface = font.render(user_text, True, (255, 255, 255))
screen.blit(text_surface, (input_rect.x + 5, input_rect.y + 8))
# Adjust box width based on text length
input_rect.w = max(140, text_surface.get_width() + 20)
pygame.display.flip()
clock.tick(60)
Enhanced Text Input with Enter Key
This example adds Enter key functionality to submit text and provides visual feedback ?
import pygame
# Initialize Pygame
pygame.init()
screen = pygame.display.set_mode((700, 300))
pygame.display.set_caption('Enhanced Text Input')
clock = pygame.time.Clock()
# Font and text variables
font = pygame.font.SysFont('arial', 36)
input_text = ""
submitted_text = ""
input_active = False
# Input box rectangle
input_box = pygame.Rect(50, 100, 600, 50)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# Activate input when clicking on the box
if input_box.collidepoint(event.pos):
input_active = True
else:
input_active = False
elif event.type == pygame.KEYDOWN and input_active:
if event.key == pygame.K_RETURN:
# Submit text and clear input
submitted_text = input_text
input_text = ""
input_active = False
elif event.key == pygame.K_BACKSPACE:
input_text = input_text[:-1]
else:
input_text += event.unicode
# Fill background
screen.fill('white')
# Draw input box with different colors
box_color = 'lightgreen' if input_active else 'lightgray'
pygame.draw.rect(screen, box_color, input_box)
pygame.draw.rect(screen, 'black', input_box, 2)
# Render current input text
text_surf = font.render(input_text, True, 'black')
screen.blit(text_surf, (input_box.x + 10, input_box.y + 10))
# Show submitted text
if submitted_text:
submitted_surf = font.render(f"Submitted: {submitted_text}", True, 'blue')
screen.blit(submitted_surf, (50, 200))
# Instructions
instruction = font.render("Click box and type. Press Enter to submit.", True, 'gray')
screen.blit(instruction, (50, 50))
pygame.display.flip()
clock.tick(60)
pygame.quit()
Key Components Explained
| Component | Purpose | Key Events |
|---|---|---|
| pygame.Rect | Defines input box area | collidepoint() for clicks |
| MOUSEBUTTONDOWN | Activates/deactivates input | Mouse click detection |
| KEYDOWN | Handles text input | Character input & backspace |
| font.render() | Converts text to surface | Display text on screen |
Common Features
Text Input Handling: Use event.unicode to capture typed characters and pygame.K_BACKSPACE for deletion.
Visual Feedback: Change colors or borders to indicate when the input box is active or inactive.
Dynamic Sizing: Adjust the input box width based on text length using text_surface.get_width().
Conclusion
Creating text input boxes in Pygame involves handling mouse clicks to activate the input area and keyboard events to capture user typing. Use visual feedback like color changes to show the active state, and implement features like Enter key submission and backspace deletion for a complete user experience.
