Skip to main content
 首页 » 编程设计

python之在 Python 3 中识别按键的代码

2024年10月24日9jackei

Python 3 是否可以识别按键?例如,如果用户按下向上箭头,程序将做一件事,而如果按下向下箭头,程序将做另一件事。

我指的不是用户必须在 keypress 之后按 enter 的 input() 函数,我的意思是程序将 keypress 识别为按下的某个按键。

这个问题是不是太绕了? xD

请您参考如下方法:

Python 有一个 keyboard具有许多功能的模块。您可以在 Shell 和 Console 中使用它。 安装它,也许使用这个命令:

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 

它还检测整个窗口的 key 。
谢谢。