美文网首页
python 获得键盘事件

python 获得键盘事件

作者: proud2008 | 来源:发表于2020-07-16 17:09 被阅读0次

    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
    

    相关文章

      网友评论

          本文标题:python 获得键盘事件

          本文链接:https://www.haomeiwen.com/subject/npqmhktx.html