识别Python中按键的代码3
问题描述:
python 3有没有办法识别按键?例如,如果用户按下向上箭头,程序会做一件事,而如果按下向下箭头,程序会做其他事情。识别Python中按键的代码3
我不是指用户必须在按键之后按下输入的input()函数,我的意思是程序在某处按键时识别按键的位置。
这个问题太混乱了吗?的xD
答
我想这是一个GUI程序,
如果使用内置的GUI模块Tkinter的,可以使用绑定的功能连接到一个按键。
main.bind('<Up>', userUpkey)
其中userUpKey是在当前范围中定义的函数。
答
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('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的关键。
谢谢。
谢谢你的回答(我实际上并没有编写一个程序,这只是一个普通的查询),但是你知道它是否可以在命令行(而不是GUI)中使用吗? –
我会看着诅咒。我没有亲自使用它,所以我不会尝试一个例子。 – tink3r