0

So, I have made a class 'TEXT BOX'. It has a Boolean variable used to track its state (active/inactive). It also has some methods to input and display the text on the screen and also to remove text on pressing backspace. For some reason, it doesn't seem to respond. Can anyone help explain it?

    """
    A Textbox Class
    """

    def __init__(self, x: int, y: int, text_height: int, padding: int, length: int, inactive_colour: tuple,
                 active_colour: tuple, border_thickness: int):
        self.x = x
        self.y = y
        self.padding = padding
        self.text_height = text_height
        self.length = length
        self.inactive_colour = inactive_colour
        self.active_colour = active_colour
        self.border_thickness = border_thickness
        self.rect = pygame.Rect(self.x, self.y, self.length, self.text_height + self.padding)
        self.active = False
        self.text = ''
        self.font = pygame.font.SysFont("Segeo UI", self.text_height)

    def draw_box(self, screen):
        if self.active:
            pygame.draw.rect(screen, self.active_colour, self.rect, width=self.border_thickness)
        else:
            pygame.draw.rect(screen, self.inactive_colour, self.rect, width=self.border_thickness)

    def render_text(self, screen):
        display_text = self.font.render(self.text, True, (255, 255, 255))
        text_pos = (self.x + self.padding, self.y + self.padding)
        screen.blit(display_text, text_pos)
        self.draw_box(screen)

    def get_text(self):
        return self.text

    def input_text(self):
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN and not self.active:
                self.active = self.rect.collidepoint(pygame.mouse.get_pos())

            elif self.active and event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    self.active = False
                elif event.key == pygame.K_BACKSPACE:
                    self.text = self.text[:-1]
                    print(self.text)
                else:
                    self.text = self.text + event.unicode
                    print(self.text)``` 
  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 13 '22 at 13:49
  • You should not call `pygame.event.get()` in `input_text`. Pygame has an event queue where it puts all events. `pygame.event.get()` returns these events and clears them afterwards. So you should only use it once and than loop over it. `events = pygame.event.get()` – Jerry Oct 13 '22 at 14:03

0 Answers0