1

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

因此,我在下面尝试了:

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

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

4

1 回答 1

1

根据文档 ( 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)
于 2021-05-23T20:10:18.353 回答