如何为文本框创建类?

2024-05-18 20:15:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用PyGame1.9.6和Python3.7.4。我想为用户输入的文本框创建一个类。但我不知道如何做到这一点的逻辑。我昨天开始了面向对象编程。因此,我想了解如何为下面的代码创建一个类

import pygame

pygame.init()

screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
base_font = pygame.font.Font(None, 32)
user_text = ''

input_rect = pygame.Rect(100, 200, 140, 32)
color_active = pygame.Color('lightskyblue3')
color_passive = pygame.Color('gray15')
color = color_passive

active = False

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            if input_rect.collidepoint(event.pos):
                active = True
            else:
                active = False

        if event.type == pygame.KEYDOWN:
            if active == True:
                if event.key == pygame.K_BACKSPACE:
                    user_text = user_text[:-1]
                else:
                    user_text += event.unicode

    screen.fill((190, 70, 60))
    if active:
        color = color_active
    else:
        color = color_passive
    pygame.draw.rect(screen, color, input_rect, 2)

    text_surface = base_font.render(user_text, True, (255, 255, 255))
    screen.blit(text_surface, (input_rect.x + 5, input_rect.y + 5))

    input_rect.w = max(100, text_surface.get_width() + 10)

    pygame.display.update()
    clock.tick(60)

正如您所看到的,这是一个文本框的大量代码。但是,我如何设置逻辑、参数以及什么不可以这样做呢。一如既往地感谢您的投入和建议。我喜欢


Tags: textrecteventfalsetrueinputifscreen

热门问题