如何使用python(和Gtk3)制作全局键盘快捷键?

Phl*_*lya 4 python keyboard-shortcuts pygobject gtk3

我想制作像 t 这样的键盘快捷键,当主窗口关闭时它会起作用(但进程正在运行,因为程序有一个统一的应用程序)。我看到了一个包 keybinder,但似乎不能将它与 Gtk3 和 pygobject 一起使用。还是可以?那怎么办?如果没有,有没有其他方法可以做到这一点?该应用程序适用于 linux (ubuntu),我使用 python 2.7。

Rob*_*ans 5

Keybinder 适用于 python3、Gtk3 和 pygi。源代码树中没有工作示例。

#!/usr/bin/env python3
"""
example-gi-py3.py

Looked at a pull request that was built for py2.x, but
overwrote the original py instead of making a separate example.
I wouldn't have accepted that pull request either.

The keybinder.init() part wasn't in the original example.

aking1012.com@gmail.com

public domain
"""

import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Keybinder', '3.0')

from gi.repository import Gtk
from gi.repository import Keybinder

def callback(keystr, user_data):
    print ("Handling", user_data)
    print ("Event time:", Keybinder.get_current_event_time())
    Gtk.main_quit()

if __name__ == '__main__':
    keystr = "<Ctrl><Alt>M"
    Keybinder.init()
    Keybinder.bind(keystr, callback, "keystring %s (user data)" % keystr)
    print ("Press", keystr, "to handle keybinding and quit")
    Gtk.main()  
Run Code Online (Sandbox Code Playgroud)

注意:没有经过彻底的测试,但作为一个简单的例子,它似乎有效。