请问有没有人知道Python怎么检测按键按下啊,比如按一下空格打印一串文字

C++的也发一下?

keypress·python
168 views
Comments
登录后评论
Sign In
·

用这个库keyboard,可以模拟按键,点击,组合键等,安装

pip install keyboard

用这个库pynput可以监听按键事件,安装:

pip install pynput

监听:

from pynput import keyboard

# 返回 False 关闭监听
def on_press(key):
    if key == keyboard.Key.esc:
        return False  
    try:
        k = key.char  # 监听单按键
    except:
        k = key.name
    if k in ['1', '2', 'left', 'right']:
        print('Key pressed: ' + k)
        return False

listener = keyboard.Listener(on_press=on_press)
listener.start()  
listener.join()