【问题标题】:How to make global keyboard shortcuts with python (and Gtk3)?如何使用 python(和 Gtk3)制作全局键盘快捷键?
【发布时间】:2013-05-17 15:59:46
【问题描述】:

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

【问题讨论】:

  • 添加了注释,它也适用于 2.7,我只是不想弄乱我的磁盘。我保持 2.7 的原始状态,并在 py3k 上做所有值得做的事情。

标签: python keyboard-shortcuts gtk3 pygobject


【解决方案1】:

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

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

【讨论】:

  • 添加了注释,我在 github 上提出了一个拉取请求,这个示例没有按照原始示例进行。也许那个人会被拉进来。
【解决方案2】:

我还使用 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/

但请注意,如果您正在使用另一个应用程序并且您的应用程序在后台运行,这也会窃取焦点。

【讨论】:

    猜你喜欢
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多