在Python 3中注册热键,可以使用第三方库`pyhotkey`。以下是使用`pyhotkey`注册热键的基本步骤:
1. 安装`pyhotkey`库:
pip install pyhotkey
2. 导入`pyhotkey`库并使用`Manager`类注册热键:
from pyhotkey import Manager
def hello_world():
print("键盘触发的魔法~")
创建热键管理器
hotkey = Manager()
注册热键
hotkey.register(('ctrl', 'h'), callback=hello_world)
开始监听热键
hotkey.listen()
上述代码中,`hello_world`函数将在按下`Ctrl+H`组合键时被调用。
3. 如果需要注册多个热键或更复杂的组合键,可以这样做:
from pyhotkey import Manager
def task1():
print("任务1启动")
def task2():
print("任务2启动")
创建热键管理器
hotkey = Manager()
注册多个热键
hotkey.register(('ctrl', 'shift', '1'), callback=task1)
hotkey.register(('alt', 'x'), callback=task2)
开始监听热键
hotkey.listen()
在这个例子中,`task1`函数会在按下`Ctrl+Shift+1`组合键时被调用,`task2`函数会在按下`Alt+X`组合键时被调用。
4. 如果需要注册带参数的回调函数,可以这样做:
from pyhotkey import Manager
def say_something(text):
print(f"你触发了: {text}")
创建热键管理器
hotkey = Manager()
注册带参数的热键
hotkey.register(('ctrl', 'u'), callback=say_something, args=("你好,世界!"))
开始监听热键
hotkey.listen()
在这个例子中,`say_something`函数会在按下`Ctrl+U`组合键时被调用,并打印出传递给它的参数。
请注意,热键注册后,程序将持续监听这些热键,直到程序被关闭。如果你需要在某个条件下停止监听热键,可以在`hotkey.listen()`之前调用`hotkey.stop()`方法。