首页 > 解决方案 > 有人可以用 pygame 帮助我编写用于切换按钮的代码吗?

问题描述

def box_button(x,y, colour, action=None):
    toggle = False
    pos = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if click[0] == 1 and (x + 10) + 30 > pos[0] > (x + 10) and (y + 10) + 30 > pos[1] > (y + 10):
        if toggle == True:
            toggle = False
            colour = red
        else:
            toggle = True
            colour = green
    pygame.draw.rect(window, white, (x, y, 50, 50))
    pygame.draw.rect(window, colour, (x + 10, y+10, 30, 30))
    return colour

任何人都可以帮助此代码,以便它可以帮助我将按钮从红色切换到绿色?每次我单击带有此代码的按钮时,它都会在我左键单击时变为绿色,但是当我松开单击时,它又变回红色,我希望它永久保持绿色?谢谢

标签: pythonpygame

解决方案


click[0] == 1是 True,只要按钮被按住。您必须实施该MOUSEBUTTONDOWN事件。

获取主应用程序循环中的事件列表:

events = pygame.event.get()
for event in events:
    if event.type == pygame.QUIT:
        # [...]

添加一个events参数box_button并将事件列表传递给函数:

box_button(events, .....)

检查MOUSEBUTTONDOWN事件box_buttonpygame.Rect分别collidepoint用于碰撞测试:

def box_button(events, x, y, colour, action=None):
    toggle = False

    for event in events:
        if event.type == pygame.MOUSEBUTTONDOWN:
            button_rect = pygame.Rect(x + 10, y+10, 30, 30)
            if event.button == 1 and button_rect.collidepoint(event.pos):
                toggle = not toggle
                colour = green if toggle else red

    pygame.draw.rect(window, white, (x, y, 50, 50))
    pygame.draw.rect(window, colour, (x + 10, y+10, 30, 30))
    return colour

推荐阅读