【问题标题】:Pygame button won't work on press/only on hoverPygame按钮在按下/仅在悬停时不起作用
【发布时间】:2012-06-16 04:57:51
【问题描述】:

我正在尝试让 onclick 按钮打印支票并运行我的铅笔功能。目前,如果我将鼠标悬停在 Box sprite 上……它将运行打印和铅笔功能。它应该是 ONCLICK 它运行那些 2。任何人都可以帮助我吗?谢谢! (这应该是所有相关代码,如果您需要更多,请告诉我:)

class Box(pygame.sprite.Sprite):
def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = pygame.Surface((35, 30))
    self.image = self.image.convert()
    self.image.fill((255, 0, 0))
    self.rect = self.image.get_rect()
    self.rect.centerx = 25
    self.rect.centery = 505
    self.dx = 10
    self.dy = 10

while keepGoing:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            keepGoing = False
        box = Box()
        allSprites = pygame.sprite.Group(box)   
        allSprites.draw(screen)

        if event.type == MOUSEMOTION:
            x,y = event.pos
            if box.rect.collidepoint(x,y) and pygame.MOUSEBUTTONUP:                      
                print("collide works")
                pencil(background,clock,keepGoing,screen)
        pygame.display.flip()

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    您的代码不是检查鼠标点击,而是检查鼠标移动。

    如果您想测试对您的框的点击,请更改条件以检查 MOUSEBUTTONDOWNMOUSEBUTTONUP 事件(取决于您想要对点击的哪一部分做出反应),而不是 MOUSEMOTION 事件.

    不过,您的代码还有其他一些问题。例如,您在每次活动后创建您的 Box 和 Group。可能您只想在进入游戏循环之前创建它们一次(这将更有意义且性能更好)。

    【讨论】:

    • 叹息...谢谢。我现在觉得很傻。我见过的所有示例/教程等.. 让您看起来像是在检查鼠标运动.. 然后检查发生的鼠标事件(即 mousedown)。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2017-04-14
    相关资源
    最近更新 更多