I am making a game using pygame, and I would like my user to type in a textbox when they are asked a question.
I looked this up, and came up with this code:
base_font = pygame.font.Font(None, 32)
user_text = ''
input_rect = pygame.Rect(A-140, B-32, 140, 32)
color_active = pygame.Color('lightskyblue3')
color_passive = (100, 100, 100)
color = color_passive
active = False
textbox = True
def textbox_update():
global active
global input_rect
global color
global user_text
if not textbox:
return
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if input_rect.collidepoint(event.pos):
active = True
else:
active = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
user_text = user_text[:-1]
else:
user_text += event.unicode
if active:
color = color_active
else:
color = color_passive
pygame.draw.rect(screen, color, input_rect)
text_surface = base_font.render(user_text, True, (255, 255, 255))
screen.blit(text_surface, (input_rect.x+5, input_rect.y+5))
input_rect.w = max(100, text_surface.get_width()+10)
pygame.display.flip()
But this works horribly, and fails to grab input most of the time. Here is a working example I put together that shows how terrible this is:
import pygame
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((500,600))
base_font = pygame.font.Font(None, 32)
user_text = ''
input_rect = pygame.Rect(250, 300, 140, 32)
color_active = pygame.Color('lightskyblue3')
color_passive = (100, 100, 100)
color = color_passive
active = False
textbox = True
done = False
def textbox_update():
global active
global input_rect
global color
global user_text
if not textbox:
return
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if input_rect.collidepoint(event.pos):
active = True
else:
active = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
user_text = user_text[:-1]
else:
user_text += event.unicode
if active:
color = color_active
else:
color = color_passive
pygame.draw.rect(screen, color, input_rect)
text_surface = base_font.render(user_text, True, (255, 255, 255))
screen.blit(text_surface, (input_rect.x+5, input_rect.y+5))
input_rect.w = max(100, text_surface.get_width()+10)
pygame.display.flip()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill((255,255,255))
textbox_update()
pygame.display.update()
Why does this not work?