python 获得键盘事件

2020-07-16  本文已影响0人  proud2008

pip install pynput

https://pypi.org/project/pynput/

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    # print(type(key))
    # print(hasattr(key,'char'))
    if hasattr(key,'char'):
        k = key.char  # single-char keys a b c
    else:
        k = key.name  # other keys left right ctrl shift

    # try:
    #     k = key.char  # single-char keys a b c
    # except Exception as err:
    #     print(err)
    #     k = key.name  # other keys left right ctrl shift
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return True  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys
上一篇下一篇

猜你喜欢

热点阅读