Bootstrap SomeTools Icon
返回
【1】方式一
from pynput import keyboard
def on_press(key):
    try:
        print('字母键: {} 被按下'.format(key.char))
    except AttributeError:
        print('特殊键: {} 被按下'.format(key))


def on_release(key):
    print('{} 释放了'.format(key))
    if key == keyboard.Key.esc:
        # 释放了esc 键,停止监听
        return False

【2】方式二
from pynput import keyboard
# 监听键盘键入
with keyboard.Events() as events:
    for event in events:

        # 监听esc键,释放esc键,停止监听。
        if event.key == keyboard.Key.esc:
            print('接收到事件 {}, 停止监听'.format(event))
            break
        else:
            if isinstance(event, keyboard.Events.Press):
                print('按下按键 {} '.format(event))
            elif isinstance(event, keyboard.Events.Release):
                print('松开按键 {}'.format(event))