Este módulo fornece duas classes de utilitário que simplificam a entrada de texto usando o Pygame. As aulas são:
TextInputVisualizer que pode ser usado para gerenciar e desenhar entrada de texto. Basta passar em todos os eventos retornados pelo pygame.event.get() a ele em todos os quadros e preencher seu atributo surface na tela.TextInputManager que pode ser usado para gerenciar apenas o texto inserido, sem aspecto visual. Usado pelo TextInputVisualizer nos bastidores.A maneira mais simples está usando o Pypi:
python3 -m pip install pygame-textinput
TextInputVisualizer Todos os argumentos para o construtor são opcionais. Uma vez construído, ligue update todos os quadros com todos os eventos do Pygame como um argumento, depois o campo surface da tela, como assim:
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 os argumentos são opcionais.
| Argumento | Descrição |
|---|---|
| gerente | O TextInputManager usado para gerenciar a entrada |
| font_object | O objeto pygame.font.Font usado para renderizar |
| Antialias | se deve renderizar a fonte antialiasse |
| font_color | cor da fonte renderizada |
| CURSOR_BLINK_INTRAL | O intervalo do cursor piscando, em MS |
| cursor_width | A largura do cursor, em pixels |
| cursor_color | A cor do cursor |
Todos os argumentos acima também são campos que podem ser acessados e modificados em tempo real, por exemplo, como este:
textinput . cursor_width = 12
textinput . value = "Hello, World!"
print ( textinput . font_color )| Campo | Descrição |
|---|---|
| valor | (string) o texto inserido até agora |
| superfície | O objeto pygame.Surface com texto e cursor inseridos nele e um fundo transparente. Não pode ser definido. |
| cursor_visible | (Bool) se o cursor está atualmente visível ou não. Vira todos cursor_interval MS, desde que update seja chamada continuamente. |
| Método | Descrição |
|---|---|
| Atualização (eventos) | Chame esse método de todos os quadros enquanto a entrada deve ser processada e cursor_visible deve ser atualizado. |
for event in events :
...
if event . type == pygame . KEYDOWN and event . key == pygame . K_RETURN :
print ( "Oooweee" )pygame : pygame . key . set_repeat ( 200 , 25 ) # press every 50 ms after waiting 200 ms Esta nova versão também foi otimizada de forma que você possa modificar qualquer campos em tempo real e a superfície real só renderá se você o acessar usando textinput.surface - e somente se você realmente modificar algum valores.
TextInputManager Se você preferir desenhar o texto na tela, pode usar TextInputManager para gerenciar apenas a string que foi digitada até agora.
Como TextInputVisualizer , você alimenta o método update , todos os eventos recebidos pelo pygame.event.get() que deseja processar. TextInputVisualizer faz isso por você dentro do método update se você passar por um TextInputManager .
| Argumento | Descrição |
|---|---|
| inicial | O valor inicial (texto) |
| Validador | Uma função pegando uma string e retornando um bool . Toda vez que uma entrada modifica o valor, essa função é chamada com o valor modificado como um argumento; Se a função retornar True , a entrada será aceita, caso contrário, a entrada será ignorada. |
Então diga que você deseja permitir apenas a entrada de até 5 letras, você pode fazer isso com
manager = TextInputManager ( validator = lambda input : len ( input ) <= 5 )| Campo | Descrição |
|---|---|
| valor | O valor inserido até agora. Quando muda, cursor_pos é mantido o mais longe possível. |
| cursor_pos | A posição do cursor. 0 está diante do primeiro caractere, len(manager.value) a posição após a última. Os valores fora desse intervalo estão presos. |
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 )