Создание текстового поля пользовательского ввода в Python с использованием Pygame

Чтобы создать текстовое поле пользовательского ввода в Python с помощью Pygame, вы можете использовать следующие методы:

Метод 1: pygame.draw.rectи pygame.font.FontPygame:

import pygame
pygame.init()
# Set up the screen
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("User Input Text Box")
# Set up the colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Set up the font
font = pygame.font.Font(None, 32)
# Set up the text box rectangle
input_rect = pygame.Rect(300, 250, 200, 32)
# Set up the default text
text = ""
# Run the game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                print(text)  # Do something with the entered text
                text = ""  # Clear the text box
            elif event.key == pygame.K_BACKSPACE:
                text = text[:-1]
            else:
                text += event.unicode
    # Clear the screen
    screen.fill(WHITE)
    # Render the text
    txt_surface = font.render(text, True, BLACK)
    # Blit the text
    screen.blit(txt_surface, (input_rect.x + 5, input_rect.y + 5))
    # Draw the text box rectangle
    pygame.draw.rect(screen, BLACK, input_rect, 2)
    # Update the display
    pygame.display.flip()
# Quit the game
pygame.quit()

Метод 2: модуль pygame_textinputPygame (сторонний модуль, необходимо установить):

import pygame_textinput
# Set up the input box
input_box = pygame_textinput.TextInput()
# Run the game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # Get the user input
    input_box.update(pygame.event.get())
    # Clear the screen
    screen.fill(WHITE)
    # Render the text
    screen.blit(input_box.get_surface(), (10, 10))
    # Update the display
    pygame.display.flip()
# Quit the game
pygame.quit()

Обратите внимание, что для второго метода вам необходимо установить модуль pygame_textinputотдельно.