在python中检测按键?

2024-04-24 11:17:49 发布

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


Tags: python
3条回答

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('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break

正如OP提到的raw_输入-这意味着他想要cli解决方案。 Linux:你想要的是curses(windows PDCurses)。Curses,是一个用于cli软件的图形API,您可以实现不仅仅是检测关键事件。

此代码将检测按键,直到按下新行。

import curses
import os

def main(win):
    win.nodelay(True)
    key=""
    win.clear()                
    win.addstr("Detected key:")
    while 1:          
        try:                 
           key = win.getkey()         
           win.clear()                
           win.addstr("Detected key:")
           win.addstr(str(key)) 
           if key == os.linesep:
              break           
        except Exception as e:
           # No input   
           pass         

curses.wrapper(main)

对于那些在窗户上苦苦寻找有效答案的人,我的答案是:pynput

from pynput.keyboard import Key, Listener

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

上述功能将打印您按的任何键,并在您释放“esc”键时启动操作。键盘文档是here,用于更多变的用法。

Markus von Broady强调了一个潜在的问题,即:此答案不要求您处于激活此脚本的当前窗口中,windows的解决方案是:

from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be

if current_window == desired_window_name:

    with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
        listener.join()

相关问题 更多 >