无论如何python 3都能识别出按键吗?例如,如果用户按下向上箭头,程序将执行一项操作,而如果按下向下箭头,程序将执行其他操作。
我不是指用户在按键后必须按Enter键的input()函数,我的意思是程序将按键识别为按下按键的位置。
这个问题太混乱了吗? xD
答案 0 :(得分:1)
Python有一个keyboard模块,具有许多功能。您可以在 Shell 和控制台中使用它。 安装它,也许使用此命令:
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('up'): #if key 'up' is pressed.You can use right,left,up,down and others
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
您可以将其设置为多个密钥检测:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
你也可以这样做:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'):
#then do this
它还检测整个Windows的关键字 感谢。
答案 1 :(得分:0)
我认为这是一个gui程序,
如果使用内置的gui模块Tkinter,您可以使用bind将功能连接到按键。
main.bind('<Up>', userUpkey)
其中userUpKey是当前作用域中定义的函数。