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

标签 python python-3.x python-3.4 keypress python-3.3

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

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

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

最佳答案

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

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 。
谢谢。

关于python - 在 Python 3 中识别按键的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35688969/

相关文章:

python-3.x - `concurrent.futures.map` 是线程安全的吗?

Python 线程 self._stop() 'Event' 对象不可调用

python - 如何从 Kivy 中的一组小部件动态创建纹理?

python - 如何在 64 位组件上使用 win32api(或类似的)?

python - 自签名证书私钥值不匹配

python - 将行和列总和应用于 Pandas 数据框中的单元格

python - 为什么嵌套函数比非嵌套函数慢这么多?

mysql - Python 3 和 mysql 通过 SQLAlchemy

python - 从 Pandas 和 unicode 错误创建 h2o 数据框

python - 可以在 python3.4 中使用 __future__ 导入 @ 运算符吗?