我用 LinuxLinux学习|Gentoo/Arch/FreeBSD

如何在Linux上用Python实现全局快捷键绑定

2020-03-21  本文已影响0人  霡霂976447044

1 Keybinder简介

Keybinder能够在Gtk程序X 11上的一个绑定全局键位的库。
文档地址:http://pygobject-doc.gitee.io/pgi-docs/#Keybinder-3.0

2 实现绑定一个快捷键 弹出一个Gtk窗口

  1. 首先绑定快捷键, 判断绑定的快捷键是否成功 不能和其它程序的冲突
  2. 创建子进程调用exec簇函数替换当前进程的上下文环境
  3. 注册忽略子进程终止信号,启动多个相同的Gtk3程序不会共存,防止僵尸进程

代码

import gi
import os
import signal

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

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

signal.signal(signal.SIGCHLD, signal.SIG_IGN)


def run_other_window():
    pid = os.fork()
    if pid == 0:
        os.execlp('python', 'python', '../base/01-helloworld.py')
    print('run_other_window, pid', pid)


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


if __name__ == '__main__':
    keystr = "<Control><Alt>u"
    Keybinder.init()
    res = Keybinder.bind(keystr, callback, "Keystring %s (user data)" % keystr)
    if not res:
        print('绑定快捷键失败')
        exit(1)
    print("Press", keystr, "to handle keybinding and quit")
    Gtk.main()
上一篇下一篇

猜你喜欢

热点阅读