有没有办法让python 3识别一个按键?例如,如果用户按下向上箭头,程序将执行一项操作,而如果按下向下箭头,程序将执行其他操作。
我不是指input()函数,在这里用户必须在按键后按enter键,我指的是程序将按键识别为按下的按键。
这个问题是不是太混乱了?xD
发布于 2017-06-29 08:57:40
Python有一个具有许多特性的模块。您可以在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的关键字。
谢谢。
发布于 2016-02-29 06:21:13
我假设这是一个gui程序,
如果使用内置的gui模块Tkinter,可以使用bind将函数连接到按键。
main.bind('<Up>', userUpkey)其中userUpKey是在当前作用域中定义的函数。
https://stackoverflow.com/questions/35688969
复制相似问题