python - 我怎样才能让每次点击发生一次?

标签 python python-3.x pygame

当我将鼠标悬停在按钮上时,它会改变颜色,但我还想在单击它时将数字添加到列表中。我得到它来添加数字,但我希望每次点击只发生一次,

def button():
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if mouse[0] < 300 and mouse[1] < 300:
        topleft.color = (255, 0, 0)
        if click[0]:
            playerpattern.append(1)
    else:
        topleft.color = (100, 0, 0)

playerpattern = []

while playing:

    print(str(playerpattern))        

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            playing = False

    button()
    win.fill((0, 0, 0))
    pygame.display.update()

pygame.quit()

如果按住单击,它只会发送垃圾邮件 1。因此,如果您单击 1 秒的时间过长,则会添加两个 1。

最佳答案

这是@TheLazyScripter 代码的一个刺探...

def button_hover():
    mouse = pygame.mouse.get_pos()

    if mouse[0] < 300 and mouse[1] < 300:
        topleft.color = (255, 0, 0)
    else:
        topleft.color = (100, 0, 0)

def clicky_button():
    mouse = pygame.mouse.get_pos()
    if mouse[0] < 300 and mouse[1] < 300:
        playerpattern.append(1)

playerpattern = []

while playing:

    print(str(playerpattern))        

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            playing = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            clicky_button()

    button_hover()
    win.fill((0, 0, 0))
    pygame.display.update()

pygame.quit()

本质上,您在 for 循环中检查多种事件类型。将悬停代码与点击代码隔离开来,因为您可以悬停而不点击。当你悬停时,改变颜色。单击时,执行单击代码。

关于python - 我怎样才能让每次点击发生一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56572717/

相关文章:

python - sge-pygame 旋转父子 Sprite

python - 无法在 pygame 中正确执行射弹操作

python - 除了使用词袋等向量表示之外,还有哪些特征对句子分类有好处?

python - 在IPython中运行ProcessPoolExecutor

给定字符串路径的 Python 弹出嵌套 Json 键

python - pygame贪吃蛇游戏,蛇在快速改变方向时不会移动

c# - 您可以将 Python 嵌入到 C 程序中,然后在不使用外部工具的情况下从 C#/ASP.NET 调用它吗?

Python 将时间增量转换为字符串格式的小时

python - 生成器未按预期关闭数据

python-3.x - 如何使多个对象同时工作?