如何解决遵循视频指南时,pynput 自定义自动键脚本不起作用
我想创建一个热键,但决定使用 Python 而不是 AHK 来“挑战”自己。
我想在按下组合键 Ctrl+Alt+P(或 p)时打印出短语 Scheiße!
我参考了 this 视频并编写了以下脚本:
from pynput import keyboard
COMBINATIONS = [
{keyboard.Key.ctrl,keyboard.Key.alt,keyboard.KeyCode(char='p')},# Detects ctrl+alt+p
{keyboard.Key.ctrl,keyboard.KeyCode(char='P')} # Detects ctrl+alt+P
]
current = set()
def execute():
print ("Scheiße!") # When the above combo is pressed,the word "Scheiße!" is printed
def on_press(key):
if any([key in COMBO for COMBO in COMBINATIONS]): # Checks if pressed key is in any combinations
current.add(key) # If it is,then it's added to the current key set
if any(all (k in current for k in COMBO) for COMBO in COMBINATIONS): # Checks if every key of the combination has been pressed
execute() # If all checks pass,execute is called
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]): # Checks if a key released is in any of the combinations
current.remove(key) # If it is,then it's remove from the current key set if applicable
with keyboard.Listener(on_press=on_press,on_release=on_release) as listener:
listener.join()
当我执行脚本时,出现以下错误:
================== RESTART: C:\Users\imsOASIAN\Desktop\Scheiße!.py =================
Unhandled exception in listener callback
Traceback (most recent call last):
File "C:\Users\imsOASIAN\AppData\Local\Programs\Python\python39\lib\site-packages\pynput\_util\__init__.py",line 211,in inner
return f(self,*args,**kwargs)
File "C:\Users\imsOASIAN\AppData\Local\Programs\Python\python39\lib\site-packages\pynput\keyboard\_win32.py",line 287,in _process
self.on_release(key)
File "C:\Users\imsOASIAN\AppData\Local\Programs\Python\python39\lib\site-packages\pynput\_util\__init__.py",line 127,in inner
if f(*args) is False:
File "C:\Users\imsOASIAN\Desktop\Scheiße!.py",line 20,in on_release
current.remove(key) # If it is,then it's remove from the current key set if applicable
KeyError: 'p'
Traceback (most recent call last):
File "C:\Users\imsOASIAN\Desktop\Scheiße!.py",line 23,in <module>
listener.join()
File "C:\Users\imsOASIAN\AppData\Local\Programs\Python\python39\lib\site-packages\pynput\_util\__init__.py",line 259,in join
six.reraise(exc_type,exc_value,exc_traceback)
File "C:\Users\imsOASIAN\AppData\Local\Programs\Python\python39\lib\site-packages\six.py",line 702,in reraise
raise value.with_traceback(tb)
File "C:\Users\imsOASIAN\AppData\Local\Programs\Python\python39\lib\site-packages\pynput\_util\__init__.py",then it's remove from the current key set if applicable
KeyError: 'p'
我尝试了各种故障排除步骤,例如删除德语字符、用其他键替换“p”和“alt”,但唯一能做的就是更改输出。
有没有人有解决方案?
解决方法
根据你提供的信息,我在VS Code中测试了视频中的代码,可以在VS Code中运行:
请使用代码:
COMBINATIONS = [
{keyboard.Key.shift,keyboard.KeyCode(char='p')},# Detects ctrl+alt+p
{keyboard.Key.shift,keyboard.KeyCode(char='P')} # Detects ctrl+alt+P
]
另外,请重新加载 VS Code 使其识别已安装的模块,并尝试在 VS Code 中运行几次。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。