[英]Create Keyboard Shortcut?
I am searching for a way to create a cross-platform keyboard shortcut in Python.我正在寻找一种在 Python 中创建跨平台键盘快捷键的方法。 Such that when I press something like Ctrl + C or Ctrl + Alt + F , the program will run a certain function.这样当我按下Ctrl + C或Ctrl + Alt + F之类的东西时,程序将运行某个功能。
Does there exist such method or library?是否存在这样的方法或库?
I don't know is it possible to send combinations of Ctrl and/or alt.我不知道是否可以发送 Ctrl 和/或 alt 的组合。 I tried couple of times but I think it doesn't work.我尝试了几次,但我认为它不起作用。 (If someone has any other information please correct me). (如果有人有任何其他信息,请纠正我)。 What you can do is something like this:你可以做的是这样的:
from msvcrt import getch
while True:
key = ord(getch())
if key == 27: #ESC
PrintSomething()
def PrintSomething():
print('Printing something')
this will run a scrpit every time you press ESC although it will only work when you run it in command prompt.这将在您每次按 ESC 时运行一个脚本,尽管它仅在您在命令提示符下运行时才有效。
You can create a listener for keypress event by pynput
library.您可以通过pynput
库为按键事件创建侦听器。 this is a simple code that run a function when press CTRL+ALT+H
keys:这是一个简单的代码,当按下CTRL+ALT+H
键时运行一个函数:
from pynput import keyboard
def on_activate():
print('Global hotkey activated!')
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
Try keyboard
.试试keyboard
。 It can be installed with pip install keyboard
, and the Ctrl + C example can be accomplished with the syntax:可以使用pip install keyboard
, Ctrl + C示例可以使用以下语法完成:
import keyboard
keyboard.add_hotkey("ctrl + c", print, args=("Hello", "world!"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.