Как заставить функцию python работать только при нажатии клавиши?

Я пытаюсь сделать простую программу, в которой, когда вы удерживаете «w», она движется вперед, используя forward (), но когда вы отпускаете, она останавливает двигатели, используя stop(). В настоящее время я могу заставить его непрерывно двигаться вперед только при нажатии «w» и останавливаться только при нажатии другой клавиши. Вот мой код

#!/usr/bin/env python3
 # so that script can be run from Brickman

 import termios, tty, sys, time
 from ev3dev.ev3 import *

 # attach large motors to ports B and C, medium motor to port A
 motor_left = LargeMotor('outA')
 motor_right = LargeMotor('outD')
 motor_a = MediumMotor('outC')

 #==============================================

 def getch():
     fd = sys.stdin.fileno()
     old_settings = termios.tcgetattr(fd)
     tty.setcbreak(fd)
     ch = sys.stdin.read(1)
     termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

     return ch

 #==============================================

 def fire():
    motor_a.run_timed(time_sp=3000, speed_sp=600)

 #==============================================

 def forward():
    motor_left.run_forever(speed_sp=1050)
    motor_right.run_forever(speed_sp=1050)

 #==============================================

 def back():
    motor_left.run_forever(speed_sp=-1050)
    motor_right.run_forever(speed_sp=-1050)

 #==============================================

 def left():
    motor_left.run_forever(speed_sp=-1050)
    motor_right.run_forever(speed_sp=1050)

 #==============================================

 def right():
    motor_left.run_forever(speed_sp=1050)
    motor_right.run_forever(speed_sp=-1050)

 #==============================================

 def stop():
    motor_left.run_forever(speed_sp=0)
    motor_right.run_forever(speed_sp=0)

 #==============================================

 print("ready")
    k = getch()
    print(k)
    if k == 'w':
       forward()
    if k == 's':
       back()
    if k == 'a':
       left()
    if k == 'd':
       right()
    if k == 'f':
       fire()
    if k == ' ':
       stop()
    if k == 'q':
       stop()
       exit()

Любая идея о том, как сделать так, чтобы stop() запускался, когда 'w' не нажата?


person Kyle Donoghue    schedule 08.02.2017    source источник


Ответы (1)


Вы можете использовать функции KEYUP и KEYDOWN в pygame. Ниже приведен фрагмент кода, который использует для этого pygame:

import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
finished = False
isKeyPressed = False
while not finished:
    for event in pygame.event.get():
        if isKeyPressed:
            print "Key is currently pressed...Move forward!"
        if event.type == pygame.QUIT:
            finished = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                isKeyPressed = True
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_w:
                isKeyPressed = False
                #Perform action (here) when 'w' is unpressed 
        pygame.display.flip()
        clock.tick(60)
pygame.quit()
person Azeem Ghumman    schedule 08.02.2017