import pygame import sys pygame.init() display = pygame.display.set_mode((400, 300)) class TextInput(pygame.sprite.Sprite): def __init__(self, x, y, width=100, height=50, color=(0, 0, 0), bgcolor=(255, 255, 255), selectedColor=(0, 0, 255)): # Changed default bgcolor to white and selectedColor to blue super().__init__() self.text_value = "" self.isSelected = False self.color = color # Text color (black) self.bgcolor = bgcolor # Background color (white) self.selectedColor = selectedColor # Selected box color (blue) self.font = pygame.font.SysFont("Verdana", 20) self.text = self.font.render(self.text_value, True, self.color) self.bg = pygame.Rect(x, y, width, height) def render(self, display): # Update the position of the text inside the box self.pos = self.text.get_rect(center=(self.bg.x + self.bg.width / 2, self.bg.y + self.bg.height / 2)) # Draw the background box depending on whether it's selected or not if self.isSelected: pygame.draw.rect(display, self.selectedColor, self.bg) # Box color when selected else: pygame.draw.rect(display, self.bgcolor, self.bg) # Box color when not selected display.blit(self.text, self.pos) # Draw the text def clicked(self, mousePos): # Check if the mouse click is inside the box if self.bg.collidepoint(mousePos): self.isSelected = not self.isSelected return True return False def update_text(self, new_text): # Update the text and re-render it temp = self.font.render(new_text, True, self.color) if temp.get_rect().width >= (self.bg.width - 20): # Ensure text doesn't exceed the box width return self.text_value = new_text self.text = temp class CustomGroup(pygame.sprite.Group): def __init__(self): super().__init__() self.current = None TextInputGroup = CustomGroup() TextInputGroup.add(TextInput(x=100, y=100, width=200)) TextInputGroup.add(TextInput(x=100, y=200, width=200)) while True: mouse_pos = pygame.mouse.get_pos() display.fill((0, 0, 0)) # Clear the screen to white before drawing new frame for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: # Check for clicks on the text inputs for textinput in TextInputGroup: if textinput.clicked(mouse_pos): if TextInputGroup.current: TextInputGroup.current.isSelected = False textinput.isSelected = True TextInputGroup.current = textinput break if event.type == pygame.KEYDOWN: if event.key == pygame.K_BACKSPACE: # Handle backspace key press if TextInputGroup.current: TextInputGroup.current.update_text(TextInputGroup.current.text_value[:-1]) if event.key == pygame.K_RETURN: # Handle return key press (print text value) if TextInputGroup.current: print(TextInputGroup.current.text_value) if event.type == pygame.TEXTINPUT: # Update text when typing if TextInputGroup.current: TextInputGroup.current.update_text(TextInputGroup.current.text_value + event.text) # Render all the text inputs for textinput in TextInputGroup: textinput.render(display) pygame.display.update()