我一直在尝试在Python程序中检测到按键.我想找到一种方法来做到这一点,而不使用Tkinter curses,或raw_input.这是我要做的:
while True:
if keypressed==1:
print thekey
Run Code Online (Sandbox Code Playgroud)
有谁知道这有可能吗?
小智 5
Python有一个具有许多功能的键盘模块.安装它,也许使用此命令:
pip3 install keyboard
Run Code Online (Sandbox Code Playgroud)
然后在代码中使用它:
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('a'): #if key 'a' is pressed
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
Run Code Online (Sandbox Code Playgroud)
您可以设置多个密钥检测:
if keyboard.is_pressed('a') or keyboard.is_pressed('b') or keyboard.is_pressed('c'):
#then do this
Run Code Online (Sandbox Code Playgroud)