Systray阻止进一步执行代码

时间:2017-07-02 20:38:14

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

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

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才能执行,我该如何避免/修复所述行为?

1 个答案:

答案 0 :(得分: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聊天,而不会阻止其余代码,直到您决定将该主题加入主代码。