我正在用Python制作一个秒表类型的程序,我想知道如何检测是否按下了某个键(例如p表示暂停,s表示停止),我不希望它像 raw_input
那样,在继续执行之前等待用户的输入。
有人知道如何在 while 循环中执行此操作吗?
我想让这个跨平台,但如果不可能,那么我的主要开发目标是 Linux。
最佳答案
Python有一个keyboard具有许多功能的模块。安装它,也许使用以下命令:
pip3 install keyboard
然后在如下代码中使用它:
import keyboard # using module keyboard
while True: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except:
break # if user pressed a key other than the given key the loop will break
关于python - 如何检测按键按下情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54892376/