- Pygame Text Input Module
- Installation
- Usage
- Visualizer
- Arguments / Fields:
- Manager
- Arguments:
- Example
- Saved searches
- Use saved searches to filter your results more quickly
- License
- Nearoo/pygame-text-input
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Poopcode
- Code snippets | Coding interview questions with solutions | JavaScript tutorials | Python tutorials
- Python code snippet – How to make a text input box pygame?
- Curly hair, very fair, please share 🙂
Pygame Text Input Module
This module provides two utility classes that simplify entering text using pygame. The classes are:
- TextInputVisualizer which can be used to both manage and draw text input. Simply pass all events returned by pygame.event.get() to it every frame, and blit its surface attribute on the screen.
- TextInputManager that can be used to just manage inputted text, with no visual aspect. Used by TextInputVisualizer behind the scenes.
Installation
Simplest way is using pypi:
python3 -m pip install pygame-textinput
Usage
Visualizer
The easiest way is to TextInputVisualizer without any arguments. Then, feed all pygame events to its update method every frame, and blit it’s surface property to the screen. Here’s a minimal example:
This new version has also been optimized such that you can modify any fields on the fly and the actual surface will only re-render if you access it using textinput.surface — and only if you actually modified any values.
Arguments / Fields:
All these values can be both specified as arguments to the constructor and modified at later time by setting them as attributes (e.g. textinput.font_color = (255, 0, 0) ). The surface itself will only re-render once it is accessed via textinput.surface .
Argument | Description |
---|---|
manager | The TextInputManager used to manage the input |
font_object | The pygame.font.Font object used for rendering |
antialias | whether to render the font antialiased or not |
font_color | color of font rendered |
cursor_blink_interval | The interval of the cursor blinking, in ms |
cursor_width | The width of the cursor, in pixels |
cursor_color | The color of the cursor |
Manager
If you prefer to draw the text on the screen yourself, you can use TextInputManager to only manage the string that has been typed so far.
Like TextInputVisualizer , you feed its update method all events received by pygame.event.get() which you want it to process. TextInputVisualizer does this for you inside its update method if you pass it a TextInputManager .
Arguments:
Argument | Description |
---|---|
initial | The initial value (text) |
validator | A function taking a string and returning a bool . Every time the input value is modified, this function is called; if the function returns True , the input is accepted, otherwise it is ignored. |
So say you want to only allow input to up to 5 letters, you could do that with
Field Description value The inserted value so far. When change, cursor_pos is kept as far as possible. cursor_pos The position of the cursor. 0 is before the first character, len(manager.value) the position after the last. Values outside this range are clamped.
Example
Here’s an example that shows most features:
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
a small module that enables you to input text with your keyboard using pygame
License
Nearoo/pygame-text-input
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This module provides two utility classes that simplify entering text using pygame. The classes are:
- TextInputVisualizer which can be used to both manage and draw text input. Simply pass all events returned by pygame.event.get() to it every frame, and blit its surface attribute on the screen.
- TextInputManager that can be used to just manage inputted text, with no visual aspect. Used by TextInputVisualizer behind the scenes.
Simplest way is using pypi:
python3 -m pip install pygame-textinput
All arguments to the constructor are optional. Once constructed, call update every frame with all pygame events as an argument, then blit it’s surface field to the screen, like so:
import pygame_textinput import pygame pygame.init() # Create TextInput-object textinput = pygame_textinput.TextInputVisualizer() screen = pygame.display.set_mode((1000, 200)) clock = pygame.time.Clock() while True: screen.fill((225, 225, 225)) events = pygame.event.get() # Feed it with events every frame textinput.update(events) # Blit its surface onto the screen screen.blit(textinput.surface, (10, 10)) for event in events: if event.type == pygame.QUIT: exit() pygame.display.update() clock.tick(30)
All arguments are optional.
Argument | Description |
---|---|
manager | The TextInputManager used to manage the input |
font_object | The pygame.font.Font object used for rendering |
antialias | whether to render the font antialiased or not |
font_color | color of font rendered |
cursor_blink_interval | The interval of the cursor blinking, in ms |
cursor_width | The width of the cursor, in pixels |
cursor_color | The color of the cursor |
All arguments above are also fields that can be accessed and modified on the fly, e.g. like this:
textinput.cursor_width = 12 textinput.value = "Hello, World!" print(textinput.font_color)
Field | Description |
---|---|
value | (string) The text entered so far |
surface | The pygame.Surface object with entered text & cursor on it and a transparent background. Cannot be set. |
cursor_visible | (bool) wether the cursor is currently visible or not. Flips every cursor_interval ms as long as update is called continuously. |
Method | Description |
---|---|
update(events) | Call this method every frame for as long as input should be processed and cursor_visible should be updated. |
Notes on the newer version:
for event in events: . if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: print("Oooweee")
- Contrary to the old version, key-stroke repeats are not manually introduced anymore, since they can now be enabled within pygame directly:
pygame.key.set_repeat(200, 25) # press every 50 ms after waiting 200 ms
This new version has also been optimized such that you can modify any fields on the fly and the actual surface will only re-render if you access it using textinput.surface — and only if you actually modified any values.
If you prefer to draw the text on the screen yourself, you can use TextInputManager to only manage the string that has been typed so far.
Like TextInputVisualizer , you feed its update method all events received by pygame.event.get() which you want it to process. TextInputVisualizer does this for you inside its update method if you pass it a TextInputManager .
Argument | Description |
---|---|
initial | The initial value (text) |
validator | A function taking a string and returning a bool . Every time an input modifies the value, this function is called with the modified value as an argument; if the function returns True , the input is accepted, otherwise the input is ignored. |
So say you want to only allow input to up to 5 letters, you could do that with
manager = TextInputManager(validator=lambda input: len(input) 5)
Field | Description |
---|---|
value | The inserted value so far. When change, cursor_pos is kept as far as possible. |
cursor_pos | The position of the cursor. 0 is before the first character, len(manager.value) the position after the last. Values outside this range are clamped. |
import pygame import pygame.locals as pl pygame.init() # No arguments needed to get started textinput = TextInputVisualizer() # But more customization possible: Pass your own font object font = pygame.font.SysFont("Consolas", 55) # Create own manager with custom input validator manager = TextInputManager(validator = lambda input: len(input) 5) # Pass these to constructor textinput_custom = TextInputVisualizer(manager=manager, font_object=font) # Customize much more textinput_custom.cursor_width = 4 textinput_custom.cursor_blink_interval = 400 # blinking interval in ms textinput_custom.antialias = False textinput_custom.font_color = (0, 85, 170) screen = pygame.display.set_mode((1000, 200)) clock = pygame.time.Clock() # Pygame now allows natively to enable key repeat: pygame.key.set_repeat(200, 25) while True: screen.fill((225, 225, 225)) events = pygame.event.get() # Feed it with events every frame textinput.update(events) textinput_custom.update(events) # Get its surface to blit onto the screen screen.blit(textinput.surface, (10, 10)) screen.blit(textinput_custom.surface, (10, 50)) # Modify attributes on the fly - the surface is only rerendered when .surface is accessed & if values changed textinput_custom.font_color = [(c+10)%255 for c in textinput_custom.font_color] # Check if user is exiting or pressed return for event in events: if event.type == pygame.QUIT: exit() if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: print(f"User pressed enter! Input so far: textinput.value>") pygame.display.update() clock.tick(30)
About
a small module that enables you to input text with your keyboard using pygame
Poopcode
Code snippets | Coding interview questions with solutions | JavaScript tutorials | Python tutorials
Python code snippet – How to make a text input box pygame?
import pygame as pg pg.init() screen = pg.display.set_mode((640, 480)) COLOR_INACTIVE = pg.Color('lightskyblue3') COLOR_ACTIVE = pg.Color('dodgerblue2') FONT = pg.font.Font(None, 32) class InputBox: def __init__(self, x, y, w, h, text=''): self.rect = pg.Rect(x, y, w, h) self.color = COLOR_INACTIVE self.text = text self.txt_surface = FONT.render(text, True, self.color) self.active = False def handle_event(self, event): if event.type == pg.MOUSEBUTTONDOWN: # If the user clicked on the input_box rect. if self.rect.collidepoint(event.pos): # Toggle the active variable. self.active = not self.active else: self.active = False # Change the current color of the input box. self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE if event.type == pg.KEYDOWN: if self.active: if event.key == pg.K_RETURN: print(self.text) self.text = '' elif event.key == pg.K_BACKSPACE: self.text = self.text[:-1] else: self.text += event.unicode # Re-render the text. self.txt_surface = FONT.render(self.text, True, self.color) def update(self): # Resize the box if the text is too long. width = max(200, self.txt_surface.get_width()+10) self.rect.w = width def draw(self, screen): # Blit the text. screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5)) # Blit the rect. pg.draw.rect(screen, self.color, self.rect, 2) def main(): clock = pg.time.Clock() input_box1 = InputBox(100, 100, 140, 32) input_box2 = InputBox(100, 300, 140, 32) input_boxes = [input_box1, input_box2] done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True for box in input_boxes: box.handle_event(event) for box in input_boxes: box.update() screen.fill((30, 30, 30)) for box in input_boxes: box.draw(screen) pg.display.flip() clock.tick(30) if __name__ == '__main__': main() pg.quit()