pystray 与其他代码执行

pystray with other codes execution

我需要一个代码,以启动托盘图标并执行其他部分代码...

为此,我尝试了以下操作:

from pystray import MenuItem as item
import pystray
from PIL import Image, ImageDraw
import time

def action():
    pass

def exit(icon):
    icon.stop()

image = Image.open("image.PNG")
menu = (item('name', action), item('Exit', exit))
icon = pystray.Icon("A", image, "B", menu)
i = 0
icon.run()
while i != 50:
    print('test')
    time.sleep(1)
    i += 1

这会启动托盘图标,但不会执行我的循环。 (它只执行 post Icon 停止)

根据文档 (https://pystray.readthedocs.io/en/latest/reference.html),pystray.Icon.run()stop() 之前一直处于阻塞状态。你可以给它传递一个回调,尽管这将是 运行 在一个单独的线程上。

def foo(icon):
    icon.visible = True
    i = 0
    while i <= 5:
        print('test')
        time.sleep(1)
        i += 1
    print('now blocking until stop()...')

image = Image.open("image.PNG")
menu = (item('name', action), item('Exit', exit))
icon = pystray.Icon("A", image, "B", menu)
icon.run(foo)