【问题标题】:pystray with other codes executionpystray 与其他代码执行
【发布时间】:2021-05-23 18:53:36
【问题描述】:

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

所以我在下面尝试了:

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

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

【问题讨论】:

  • pystray.Icon.run() 正在阻塞(根据文档),但需要一个回调参数,您的代码可以在其中运行。 pystray.readthedocs.io/en/latest/reference.html
  • @JonSG 我也尝试添加设置,def setup(icon): icon.visible = True & icon.run(setup),但它也没有执行

标签: python python-3.x pystray


【解决方案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)

【讨论】:

    猜你喜欢
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2015-11-01
    • 2018-10-11
    • 2015-04-15
    相关资源
    最近更新 更多