按键检测

2024-03-28 23:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图在Python程序中检测按键。我想找到一种不使用Tkinter、cursesraw_input的方法。我想说的是:

while True:
    if keypressed==1:
        print thekey

有人知道这怎么可能吗?


Tags: 方法程序trueinputrawiftkinter按键
2条回答

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('a'): #if key 'a' is pressed 
            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('a') or keyboard.is_pressed('b') or keyboard.is_pressed('c'):
    #then do this

我冒昧地对你的问题稍加修改,这样才有意义,至少在Windows上有答案。(IDLE只通过tkkinter接口与键盘交互)在Windows上,答案是使用msvcrt module's console io functions

import msvcrt as ms

while True:
    if ms.kbhit():
        print(ms.getch())

对于其他系统,您必须找到等效的系统特定调用。对于posix系统,这些可能是诅咒的一部分,你说过你不可以使用,但我不知道。

当程序在默认模式下从空闲运行时,这些函数无法正常工作。对于其他图形模式ide来说也是如此。

相关问题 更多 >