Я использовал фрагмент кода, созданный пользователем @skrx, который создает поле ввода с использованием классов. Мне удалось запрограммировать код таким образом, чтобы при нажатии клавиши ввода экран закрывался и возвращал содержимое поля ввода в переменную вне класса.
Я благодарю @skrx за этот код, он очень помог.
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = pygame.Rect(x, y, w, h)
self.color = COLOR_INACTIVE
self.text = text
self.txt_surface = FONT.render(text, True, self.color)
self.active = False
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN: # If the user clicked on the input_box rect.
if self.rect.collidepoint(event.pos): # Toggle the active variable.
self.active = not self.active
else:
self.active = False # Change the current color of the input box.
self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
if event.type == pygame.KEYDOWN:
if self.active:
if event.key == pygame.K_BACKSPACE:
self.text = self.text[:-1]
else:
self.text += event.unicode # Re-render the text.
self.txt_surface = FONT.render(self.text, True, self.color)
def update(self): # Resize the box if the text is too long.
width = max(300, self.txt_surface.get_width()+10)
self.rect.w = width
def draw(self, screen):
screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5)) # Blit the text.
pygame.draw.rect(screen, self.color, self.rect, 2)# Blit the rect.
def ReturnText(self):
result = self.text
return result
Когда я нажимаю кнопку ввода на клавиатуре, код успешно проходит через InputBox.ReturnText () и закрывает окно Однако основная проблема заключается в том, что код также возвращает сообщение об ошибке:
self.txt_surface = FONT.render(self.text, True, self.color)
pygame.error: Text has zero width
Кто-нибудь знает, как это исправить? (Я не думаю, что проблема в коде @skrx, но нужно ли что-нибудь добавить?)