【问题标题】:How to make a "while mouse down" loop in pygame如何在pygame中制作“鼠标按下”循环
【发布时间】:2019-02-13 09:24:31
【问题描述】:

所以我目前在绘图应用程序中有此代码用于喷枪。当该功能处于活动状态时,它应该在画布上绘制,基本上就像喷枪一样。但是现在,我不知道如何让 pygame 检测到鼠标按下或鼠标抬起并从中循环。代码如下:

def airbrush():
    airbrush = True
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    while click == True:
        pygame.draw.circle(gameDisplay, colorChosen, (cur[0] + random.randrange(brushSize), cur[1] + random.randrange(brushSize)), random.randrange(1, 5))
        pygame.display.update()
        clock.tick(60)

现在,我的“点击时”不起作用。我应该用什么替换“单击”才能使这项工作正常进行,以便在按住鼠标时进行绘画,但是当鼠标“向上”时,它会停止?

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:

    pygame.mouse.get_pressed() 返回的状态在调用pygame.event.get() 时被评估一次。 pygame.mouse.get_pressed() 的返回值是带有按钮状态的元组。

    不要在函数中实现单独的事件处理。在主循环中做事件处理:

    done = False
    while not done:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
    
        airbrush()
        pygame.display.flip()
    

    在函数airbrush中评估当前帧的按钮(例如左键)的当前状态:

    def airbrush():
        airbrush = True
        cur = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()
        if click[0] == True: # evaluate left button
            pygame.draw.circle(gameDisplay, colorChosen, (cur[0] + random.randrange(brushSize), cur[1] + random.randrange(brushSize)), random.randrange(1, 5))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多