带有 tkinter 的 Windows 上的全局热键 [英] Global hotkey on windows with tkinter

查看:49
本文介绍了带有 tkinter 的 Windows 上的全局热键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 python tkinter 应用程序来注册一个全局热键(即使应用程序没有焦点也会触发).我找到了一些碎片,但我找不到将它们组合在一起的方法...

I want a python tkinter application to register a global hotkey (triggered even if the application has not the focus). I've found some pieces, but I can't find a way to put them together...

基本上,我可以注册热键(通过调用 windows API RegisterHotKey),但它会向 Tkinter 主循环管理下的根窗口发送WM_HOTKEY"消息,我找不到绑定它的方法...

Basically, I can register the hotkey (with a call to the windows API RegisterHotKey), but it send a "WM_HOTKEY" message to the root windows that is under Tkinter mainloop management, and I cant find a way to bind on it...

tk.protocol() 函数似乎就在那里,但这条消息似乎无法理解(我找不到已识别消息的完整列表)...

tk.protocol() function seems to be there for it, but this message seems not to be understood (I can't find a complete list of the recognized messages)...

这是一个非工作代码示例,我想在按下WIN-F3"时打印一条消息...

Here a non-working code example where I would like to print a message when "WIN-F3" is pressed...

import Tkinter
import ctypes
import win32con

class App(Tkinter.Tk): 
    def __init__(self):
        Tkinter.Tk.__init__(self)

        user32 = ctypes.windll.user32
        if user32.RegisterHotKey (None, 1, win32con.MOD_WIN , win32con.VK_F3):
            print("hotkey registered")
        else:
            print("Cannot register hotkey")

        self.protocol("WM_HOTKEY", self.hotkey_received)

    def hotkey_received(self):
        print("hotkey")

if __name__ == "__main__":
    app = App()
    app.mainloop()
    try:
        app.destroy()
    except:
        pass    

谢谢

编辑--------------------------------

EDIT --------------------------------

好的,我找到了一种方法,将整个 windows 循环推送到一个单独的线程中,独立于 tkinter 主循环.

OK, I found a way by pushing the whole windows loop in a separate thread, independent from the tkinter mainloop.

虽然我感觉这不是一个干净的解决方案,因为我实际上有 2 个循环运行,用于与操作系统进行基本相同的交互,并且它需要一个消息队列来与应用程序交互,但它可以解决问题...如果有人有更好的选择,我会很高兴看到它...

It doesn't feel like a clean solution though as I have actually 2 loops running for basically the same kind of interactions with the OS, and it require a message queue to interact with the application, but it do the trick... If someone has a better option, I would be happy to see it...

推荐答案

有点晚了,但也许对某人有帮助...阅读 这个答案.

A little bit late but maybe it would be helpful for someone... Read this answer.

这篇关于带有 tkinter 的 Windows 上的全局热键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆