Overview
ThetextEntry class creates an interactive text input field that allows users to type text. It captures keyboard input when clicked and displays the entered text.
Constructor
Parameters
The pygame surface to which the text entry field will be drawn.
The position of the text entry field on the surface.
The width and height of the text entry field.
The initial text to display in the field.
RGB color tuple for the text.
Padding around the text (currently defined but not fully utilized).
RGB color tuple for the background (parameter defined but draw() uses hardcoded white).
Methods
draw()
Draws the text entry field and handles keyboard input when the field is active.- Draws a white rectangle for the field background
- When clicked (active), captures keyboard input:
- Single characters: Added to the text (with width constraint)
- Tab: Adds 4 spaces
- Space: Adds a space
- Backspace: Removes last character
- Implements key repeat delay to prevent multiple inputs
- Updates the text overlay in real-time
mouse_click_event(pos)
Toggles the active state of the text entry field when clicked.The (x, y) position of the mouse click.
clicked attribute if the click is inside the field boundaries.
_point_is_inside(mpos)
Internal method to check if a point is inside the text entry field’s boundaries.The position to check.
True if the point is inside the field, False otherwise.
Attributes
text- The current text content of the fieldclicked- Boolean indicating if the field is active/focusedrect- The pygame.Rect defining the field boundarieslastKey- Tracks the last pressed key for delay logicdelay- Internal counter for key repeat delay
Usage Example
Fromgame.py:
Notes
- Text is rendered using “Times New Roman” font at size 25
- The field prevents text from extending beyond its width
- Key repeat delay is implemented to prevent rapid duplicate input (though the delay timing may need adjustment)
- Text wrapping is not currently implemented
- When active, the field must have pygame window focus to receive keyboard input
- The background is currently hardcoded to white in the
draw()method regardless of the bgcolor parameter