gpt4 book ai didi

python - 在没有 pygame 的情况下监听按键、按键和按键释放事件的最佳方式是什么

转载 作者:太空宇宙 更新时间:2023-11-03 17:26:10 24 4
gpt4 key购买 nike

我的树莓派机器人需要一个简单的操纵杆。由于 X 服务器问题等原因,PyGame 在我的 IDE、Eclipse 或 Putty 中无法正常工作。

为此,我想编写一个简约的按键事件监听器,但我无法使用我的代码让 python 监听按键释放事件:

import sys, tty, termios, time

#Old settings
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)

#Loop
work=0
while True:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

if "w" in ch and work==0:
work=1
print "Car goes"

if "w" not in ch and work==1:
work=0
print "Car stops"

if ch in "c":
break

如果我按住w键,就会被识别。如果我释放它,循环就会等待新的输入。

我的循环为什么以及在哪一行等待按键按下?我想用一个简约的代码来实现这一点以用于测试目的。

最佳答案

您的代码停止于

ch = sys.stdin.read(1)  

因为它尝试从 stdin 读取 1 个字符,但没有,所以它只是等待,直到有一个字符为止。

如果您想以非阻塞方式读取它,请检查以下内容: https://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/

如您所见,有多种方法可以做到这一点,但它们并不那么简单

关于python - 在没有 pygame 的情况下监听按键、按键和按键释放事件的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com