Skip to main content
 首页 » 编程设计

python之按键检测

2025年05月04日15lori

我一直在尝试在 Python 程序中检测按键。我想找到一种无需使用 Tkinter、curses 或 raw_input 即可执行此操作的方法。这就是我要说的:

while True: 
    if keypressed==1: 
        print thekey 

有谁知道这是怎么可能的?

请您参考如下方法:

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 

可以设置多个Key Detection:

if keyboard.is_pressed('a') or keyboard.is_pressed('b') or keyboard.is_pressed('c'): 
    #then do this