【问题标题】:Systray blocking further Execution of Code系统托盘阻止进一步执行代码
【发布时间】:2017-07-02 20:38:14
【问题描述】:

我发现SysTrayIcon.py 可以在 Windows 中轻松创建系统托盘图标。 问题是,它阻止了代码的进一步执行,例如,这就是我创建当前托盘图标的方式:

import _tray #This is a simple import of SysTrayIcon.py

#Create SysTray
def EXIT(self): None
def DEBUG(self): print("TEST")
def SHOW(self): print("Showing Main Window")
HOVER = "Foo v"+version
ICON = root+"apr.ico"
MENUE =(('1', None, DEBUG),
        ('2', None, SHOW),
        ('Sub', None, (
            ('Sub 1', None, DEBUG),
            ('Sub 2', None, DEBUG),)))

_tray.SysTrayIcon(ICON, HOVER, MENUE, on_quit=EXIT, default_menu_index=1)

如果我现在添加让我们说这段代码:

print("This get's executed after the Trayicon is quit.")

在我退出 Trayicon 之前它不会执行的其他代码,我怎样才能避免/修复上述行为?

【问题讨论】:

    标签: python multithreading python-3.x system-tray


    【解决方案1】:

    您可以使用线程将 WIN32 API 上下文保持与您的应用逻辑分开。例如,如果您将直接调用替换为:

    import threading
    
    def run_systray(icon, hover, menu, **options):
        _tray.SysTrayIcon(icon, hover, menu, **options)
    
    thread = threading.Thread(target=run_systray,
                              args=(ICON, HOVER, MENUE),
                              kwargs={"on_quit": EXIT, "default_menu_index": 1})
    thread.start()
    
    print("This gets executed immediately...")
    
    # you can do whatever you want here
    
    # in the end, lets cleanly handle the thread closing:
    thread.join()
    
    print("This gets executed only after systray exit...")
    

    SysTrayIcon 类将愉快地与 WIN32 API 聊天,而不会阻塞其余代码,直到您决定将线程加入主线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2017-08-20
      • 2012-09-16
      • 2015-11-01
      相关资源
      最近更新 更多