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

时间:2013-05-17 15:59:46

标签: python keyboard-shortcuts gtk3 pygobject

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

2 个答案:

答案 0 :(得分:4)

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()  

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

答案 1 :(得分:0)

我还使用Keybinder来激活Gtk3应用程序中的搜索条目字段:

from gi.repository import Keybinder
…
  class MyApp:
    …   
        Keybinder.init()
        Keybinder.bind("<Ctrl>F", self.set_search_entry_focus)
…
    def set_search_entry_focus(self, keystring):
        self.search_entry.grab_focus()

http://lazka.github.io/pgi-docs/Keybinder-3.0/

但请注意,如果您使用其他应用并且您的应用在后台运行,这也会抢占重点。