Python按键和按键释放监听器 [英] Python Key press and Key Release Listener
问题描述
我正在使用python代码控制远程玩具车.到目前为止,代码如下所示
I am controlling a remote toy car using python code .As of now the code is as below
def getkey():
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
new[6][TERMIOS.VMIN] = 1
new[6][TERMIOS.VTIME] = 0
termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
c = None
try:
c = os.read(fd, 1)
finally:
termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
return c
def car():
while True:
key = getkey()
if key == 's': #Down arrow
print "Down"
Backward()
elif key == 'w': #Up arrow
print "Up"
forward()
elif key == 'a':
print "left"
Left()
elif key == 'd':
print "Right"
Right()
elif key == 'q': #Quit
print "That's It"
break
def forward():
GPIO.output(11,True) #Move forward
当我按下'w'时,会调用forward()方法,并且汽车向前行驶,但直到我停下来 退出程序或通过其他方法调用GPIO.output(11,Flase).
When i press 'w' forward() method is called and the car moves forward but wont stop until i quit the program or call GPIO.output(11,Flase) from some other method.
有没有用于侦听任何特定键的键释放的键侦听器.
Is there any key Listener which detects key release of any particular key .
例如,如果按下"w",则调用此方法,如果释放,则调用其他方法
For example , if 'w' pressed called this method and if released call some other method
Sudo代码
if w_isPressed()
forward()
else if w_isReleased()
stop()
推荐答案
我见过 Pygame 游戏开发库在以前的类似场景中已成功使用,不仅可以处理玩具示例,还可以处理生产中的实时系统和机器.我认为这也是一个合适的候选人.检出 pygame.key
模块,了解如何使用键盘输入.
I've seen Pygame game development library being successfully used in similar scenarios before, handling realtime systems and machinery in production, not just toy examples. I think it's a suitable candidate here too. Check out pygame.key
module for what is possible to do with the keyboard input.
简而言之,如果您不熟悉游戏开发,则基本上可以连续轮询事件,例如无限"游戏循环内的输入状态更改,并做出相应的反应.通常,每个时间使用增量来更新系统参数.有很多关于Pygame的教程,并且 Pygame文档非常可靠.
In short, if you are not familiar with game development, you basically continuously poll for events such as input state changes inside an 'infinite' game loop and react accordingly. Usually update the parameters of the system using deltas per time elapsed. There's plenty of tutorials on that and Pygame available around and Pygame docs are pretty solid.
一个简单的例子:
import pygame
pygame.init()
# to spam the pygame.KEYDOWN event every 100ms while key being pressed
pygame.key.set_repeat(100, 100)
while 1:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
print 'go forward'
if event.key == pygame.K_s:
print 'go backward'
if event.type == pygame.KEYUP:
print 'stop'
您需要使用pygame.KEYDOWN
,pygame.KEYUP
和
You'll need to play with pygame.KEYDOWN
, pygame.KEYUP
and pygame.key.set_repeat
depending on how your car movement is implemented.
这篇关于Python按键和按键释放监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!