python pygame如何去除按钮?

时间:2016-06-10 20:17:04

标签: python pygame

所以即时建立一个基于pi的机器人。 它使用ps3控制器进行输入。按下X按钮时,会拍照。出于某种原因,一次需要大约5次射击。有没有办法反弹输入,所以它只能识别一次按下?

我假设它每次都注册了多个印刷机......部分代码是附加的,但我必须声明大部分代码是从piborg.org使用的

joystick = pygame.joystick.Joystick(0)

button_take_picture = 14            # X button

while running:
    # Get the latest events from the system
    hadEvent = False
    events = pygame.event.get()
    # Handle each event individually
    for event in events:
        if event.type == pygame.QUIT:
            # User exit
            running = False
        elif event.type == pygame.JOYBUTTONDOWN:
            # A button on the joystick just got pushed down
            hadEvent = True
        elif event.type == pygame.JOYAXISMOTION:
            # A joystick has been moved
            hadEvent = True
        if hadEvent:
            if joystick.get_button(button_take_picture):
                take_picture()

1 个答案:

答案 0 :(得分:1)

似乎正在发生的事情是X按钮保持向下多帧。在此期间可能会发生一些其他事件,导致在每个帧的代码中调用take_picture()。要解决此问题,您只能在take_picture()(释放按钮时)时调用JOYBUTTONUP,或将if joystick.get_button(button_take_picture)部分移至pygame.JOYBUTTONDOWN部分内。

或者,您可以使用另一个变量来指示图片是否已经拍摄,如下所示:

picture_was_taken = False

while running:
     hadEvent = False
     events = pygame.event.get()
     for event in events:
       ...
       if event.type == pygame.JOYBUTTONUP:
           if not joystick.get_button(button_take_picture)
               picture_was_taken = False
       ...
       if hadEvent:
           if joystick.get_button(button_take_picture) and not picture_was_taken:
               take_picture()
               picture_was_taken = True