我正在尝试在不阻塞主线程的情况下使用 pystray。基于 pystray 文档,我们可以使用该功能run_detached()启动而不会阻塞。
我在 Windows 上使用 pystray 所以,显然我不需要传递任何参数run_detached()来工作。
我尝试的第一件事是运行这段代码:
import pystray
from pystray import MenuItem as item
from PIL import Image, ImageTk
def show_window(icon):
print('Test')
def quit_window(icon):
icon.stop()
icon = 'icon.ico'
image=Image.open(icon)
menu=pystray.Menu(item('Show', show_window, default=True), item('Quit', quit_window))
icon=pystray.Icon("name", image, "My System Tray Icon", menu)
icon.run_detached()
但我收到了这个错误:
Exception in thread Thread-2:
Traceback (most recent call last):
File "...\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "...\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "...\lib\site-packages\pystray\_base.py", line 384, in <lambda>
threading.Thread(target=lambda: self.run(setup)).start()
NameError: name 'setup' is not defined
因此,我尝试通过更改 _base.py 中的第 384 行删除设置变量来绕过此错误
#threading.Thread(target=lambda: self.run(setup)).start()
threading.Thread(target=lambda: self.run()).start()
代码按预期工作,并创建了菜单按钮正常工作的托盘图标。
问题是当我按“退出”时,因为该stop()功能不像我使用icon.run(). 线程似乎继续运行,托盘图标保持冻结,程序没有结束。
还有另一种方法可以使这项工作正常进行吗?
编辑:我在官方 git 存储库LINK中发现了这个问题,它似乎是一个已经报告的错误。我想知道是否有可能做出解决方法。