I am making the user interface of a game and I am trying to make text input fields but they don't work. They change colour when I click on them but I can't type into them.
import pygame
pygame.init()
gui_font = pygame.font.Font(None, 30)
screen = pygame.display.set_mode([1000, 600])
class InputBoxes:
def __init__(self, pos, width, height, text=''):
# Rect
self.rect = pygame.Rect(pos, (width, height))
self.rect_colour = '#C0C0C0'
# Text
self.text = text
self.text_colour = '#000000'
self.text_look = gui_font.render(text, True, self.text_colour)
# Activate Field
self.active = False
def draw(self, screen):
pygame.draw.rect(screen, self.rect_colour, self.rect)
screen.blit(self.text_look, (0, 0))
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.rect_colour = '#E5E4E2'
else:
self.rect_colour = '#C0C0C0'
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if self.active:
if event.key == pygame.K_RETURN:
self.text = ''
print(self.text)
elif event.key == pygame.K_BACKSPACE:
self.text = self.text[:-1]
else:
self.text += event.unicode
# Re-render the text.
self.text_look = gui_font.render(self.text, True, self.text_colour)
def update(self):
width = max(200, self.text_look.get_width() + 10)
self.rect.w = width
clock = pygame.time.Clock()
tf_name = InputBoxes((40, 73), 400, 30)
tf_gameRoomName = InputBoxes((40, 113), 400, 30)
input_boxes = [tf_name, tf_gameRoomName]
host = pygame.image.load("Host.png")
# Game Loop
done = False
while not done:
for event in pygame.event.get():
screen.blit(host, (0, 0))
if event.type == pygame.QUIT:
done = True
for box in input_boxes:
box.handle_event(event)
box.draw(screen)
box.update()
pygame.display.flip()
clock.tick(30)
I am probably missing a line of code but it isn't letting me type in the boxes, however they do light up and change colour when they are clicked.