2016-06-10 233 views
0

所以即时建立一个基于pi的机器人。 它使用ps3控制器进行输入。当按下X按钮时,它会拍摄照片。出于某种原因,一次只需要5次左右的拍摄。有没有办法反弹输入,以便只识别一次按键?python pygame如何去除按钮?

我假设它的注册多个印刷机每次...部分代码连接,但我必须说明大部分是从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() 
+0

你可以阻止一个以上的调用'take_picture()'直到你得到一个'JOYBUTTONUP' – Tomer

+0

有意思,你能解释更多吗?即时通讯全新的pygame /使用按钮和即时通讯相当新的python ...这是我的第一个大项目!你会简单地'如果event.type == pygame.JOYBUTTONUP:'在'take_picture()'之前? – JONAS402

+0

是的,只有释放按钮时,才会拍照。 – Tomer

回答

1

什么似乎是发生的是X按钮停留多个帧。在此期间可能会发生其他一些事件,导致在您的代码中每帧调用take_picture()。要解决这个问题,您只能在JOYBUTTONUP(释放按钮时)拨打take_picture(),或将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 
+0

真正完美的解释!非常感谢你甚至包括变量选项。我正在思考这些问题,但是我不知道如何添加'and not'语句!希望我能给你买一杯啤酒! – JONAS402