【问题标题】:Why is the hotkey I added with the keyboard module not working?为什么我用键盘模块添加的热键不起作用?
【发布时间】:2019-05-26 00:28:47
【问题描述】:

我正在尝试使用键盘模块添加一个热键,该模块将根据使用的热键调用具有不同参数的函数。为此,我使用 python3 键盘模块。

我在这里查看文档:https://pypi.org/project/keyboard/

我希望我的程序始终处于等待不同热键的 while True 循环中。

import keyboard

def hotkey_print(word):
    print(word)


keyboard.add_hotkey('page up, page down', lambda: hotkey_print('did it work?'))

while True:
    pass

我希望它只是等待并打印“它工作了吗?”每次我按向上或向下键,但当我使用热键时没有任何反应。

【问题讨论】:

    标签: python-3.x input


    【解决方案1】:

    根据pypi,键盘库的限制之一是它应该以root身份运行:

    To avoid depending on X, the Linux parts reads raw device files (/dev/input/input*) but this requries root.
    

    因此,您可以使用su - 并成为root,然后再次运行python 文件,或者您可以使用另一个库(如果有)。

    编辑: 使用以下行而不是无限循环:

    # Block forever, like `while True`.
    keyboard.wait()
    

    【讨论】:

    • 运行没问题。我使用 sudo /home/.../python3 myscript.py 并且它运行。但是热键根本不起作用,我一直呆在while循环中,什么也没发生。
    • 删除while循环并添加以下行:keyboard.wait()
    【解决方案2】:

    我遇到了同样的问题,并且对此感到厌烦...... 只需使用pynput。 使用此模块添加热键有很多不同的方法,但我只是使用了我编写的这段代码:

    from pynput import keyboard
    
    def startHotkeys():
        if not "keysPressed" in globals():
            globals()["keysPressed"] = list()
        Thread(target=lambda: keyboard.Listener(on_press = recieveHotkey, on_release = removeHotkey).start()).start()
    
    def recieveHotkey(inputKey):
        if not inputKey in globals()["keysPressed"]:
            globals()["keysPressed"].append(inputKey)
    
    def removeHotkey(inputKey):
        while inputKey in globals()["keysPressed"]:
            globals()["keysPressed"].remove(inputKey)
    
    def hotkey(key, toRun):
        Thread(target=lambda:startHotkey(key, toRun)).start()
    
    def startHotkey(keys, toRun):
        if not "keysPressed" in globals():
            globals()["keysPressed"] = list()
        while True:
            isPressed = len(globals()["keysPressed"]) > 0 #useful hack
            if not isinstance(keys, list):
                keys = [keys]
            for i in keys:
                if not i in globals()["keysPressed"]:
                    isPressed = False
                    break
            if isPressed:
                runCodeObj(toRun)
            sleep(0.05)
    
    def runCodeObj(code):
        if isinstance(code, list):
            for i in code:
                if i:
                    i()
        else:
            if code:
                code()
    

    致电hotkey([keyboard.KeyCode(char="a"), keyboard.Key.Enter], lambda:print("you pressed enter and a at the same time")) 它永远不会停止(除非发生错误)

    hotkey(keyboard.Key.ctrl, exit)
    

    诸如此类的东西... 您需要在程序开始时调用 startHotkeys()。

    【讨论】:

      猜你喜欢
      • 2022-08-21
      • 1970-01-01
      • 2023-03-12
      • 2021-09-01
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 2014-06-12
      • 2021-08-18
      相关资源
      最近更新 更多