系统托盘阻止进一步执行代码

Systray blocking further Execution of Code

我发现 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 之前不会执行,我怎么能 avoid/fix 说行为?

您可以使用线程将 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 class 将愉快地与 WIN32 聊天 API 而不会阻塞其余代码,直到您决定将线程加入主线程。