Este módulo proporciona dos clases de utilidad que simplifican el texto de entrada usando PyGame. Las clases son:
TextInputVisualizer que se puede usar para administrar y dibujar la entrada de texto. Simplemente pase todos los eventos devueltos por pygame.event.get() a él en cada cuadro y bloquee su atributo surface en la pantalla.TextInputManager que se puede usar para administrar solo el texto entrada, sin aspecto visual. Utilizado por TextInputVisualizer detrás de escena.La forma más simple es usar PYPI:
python3 -m pip install pygame-textinput
TextInputVisualizer Todos los argumentos al constructor son opcionales. Una vez construido, llame update cada cuadro con todos los eventos de PyGame como argumento, luego brote su campo surface a la pantalla, así: así:
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 )Todos los argumentos son opcionales.
| Argumento | Descripción |
|---|---|
| gerente | El TextInputManager utilizado para administrar la entrada |
| font_object | El objeto pygame.font.Font utilizado para representar |
| antialias | si debe hacer la fuente antialiased o no |
| font_color | Color de fuentes Renderizado |
| cursor_blink_interval | El intervalo del cursor parpadeando, en la EM |
| cursor_width | El ancho del cursor, en píxeles |
| cursor_color | El color del cursor |
Todos los argumentos anteriores también son campos a los que se puede acceder y modificar en la marcha, por ejemplo, así como este:
textinput . cursor_width = 12
textinput . value = "Hello, World!"
print ( textinput . font_color )| Campo | Descripción |
|---|---|
| valor | (cadena) El texto ingresado hasta ahora |
| superficie | El objeto pygame.Surface con texto y cursor ingresado en él y un fondo transparente. No se puede configurar. |
| cursor_visible | (bool) Si el cursor es actualmente visible o no. Voltea cada cursor_interval MS siempre que update se llame continuamente. |
| Método | Descripción |
|---|---|
| Actualización (eventos) | Llame a este método cada cuadro durante el tiempo que la entrada debe procesarse y cursor_visible debe actualizarse. |
for event in events :
...
if event . type == pygame . KEYDOWN and event . key == pygame . K_RETURN :
print ( "Oooweee" )pygame directamente: pygame . key . set_repeat ( 200 , 25 ) # press every 50 ms after waiting 200 ms Esta nueva versión también se ha optimizado de tal manera que puede modificar cualquier campo en la mosca y la superficie real solo volverá a renderizar si accede a ella usando textinput.surface , y solo si realmente modificó algún valor.
TextInputManager Si prefiere dibujar el texto en la pantalla usted mismo, puede usar TextInputManager solo para administrar la cadena que se ha escrito hasta ahora.
Al igual que TextInputVisualizer , alimenta su método update todos los eventos recibidos por pygame.event.get() que desea que procese. TextInputVisualizer hace esto por usted dentro de su método update si lo pasa un TextInputManager .
| Argumento | Descripción |
|---|---|
| inicial | El valor inicial (texto) |
| validador | Una función que toma una string y devuelve un bool . Cada vez que una entrada modifica el valor, esta función se llama con el valor modificado como un argumento; Si la función devuelve True , la entrada se acepta, de lo contrario se ignora la entrada. |
Entonces, digamos que solo desea permitir la entrada de hasta 5 letras, puede hacerlo con
manager = TextInputManager ( validator = lambda input : len ( input ) <= 5 )| Campo | Descripción |
|---|---|
| valor | El valor insertado hasta ahora. Cuando cambia, cursor_pos se mantiene lo más lejos posible. |
| cursor_pos | La posición del cursor. 0 es antes del primer personaje, len(manager.value) el puesto después del último. Los valores fuera de este rango están sujetos. |
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 )