2

我有一个类,当我的 .py 程序启动时会调用它,它会在 Windows 任务栏中创建一个图标托盘。在其中,有一个选项quit,它映射到kill_icon_tray我的类中的函数,它应该终止图标,然后完成我的程序。

这是类(一些方法被省略,因为它们不是必需的):

from infi.systray import SysTrayIcon

class Tray_icon_controller:

    def __init__(self):
        self.menu_options = (("Open Chat Monitor", None, self.open_chat),)
        self.systray = SysTrayIcon("chat.ico", "Engineer Reminder", self.menu_options, on_quit=self.kill_icon_tray);

    def init_icon_tray(self):
        self.systray.start();

    def kill_icon_tray(self, systray):
        self.systray.shutdown()

但是,每当我quit在图标托盘中单击时,都会返回以下异常:

$ py engineer_reminder.py
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 237, in 'calling callback function'
  File "C:\Users\i866336\AppData\Local\Programs\Python\Python38-32\lib\site-packages\infi\systray\traybar.py", line 79, in WndProc
    self._message_dict[msg](hwnd, msg, wparam.value, lparam.value)
  File "C:\Users\i866336\AppData\Local\Programs\Python\Python38-32\lib\site-packages\infi\systray\traybar.py", line 195, in _destroy
    self._on_quit(self)
  File "C:\Users\i866336\Documents\GitHub\chat_reminder\cl_tray_icon_controller.py", line 17, in kill_icon_tray
    self.systray.shutdown()
  File "C:\Users\i866336\AppData\Local\Programs\Python\Python38-32\lib\site-packages\infi\systray\traybar.py", line 123, in shutdown
    self._message_loop_thread.join()
  File "C:\Users\i866336\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 1008, in join
    raise RuntimeError("cannot join current thread")
RuntimeError: cannot join current thread

我尝试将方法修改kill_icon_tray为此,但它引发了相同的异常:

    def kill_icon_tray(self, systray):
        self.systray.shutdown()

根据infi.systray 文档,我做得正确:

要在程序结束时销毁图标,请调用systray.shutdown()

所以我不确定我在这里错过了什么......有人可以帮忙吗?谢谢!

4

2 回答 2

0

遇到与您相同的问题,您本可以找到解决方案,但对于遇到相同问题的其他人。

为我解决的问题是将 systray.shutdown() 更改为 SysTrayIcon.shutdown

    def kill_icon_tray(systray):
    SysTrayIcon.shutdown

希望这可以帮助

于 2020-06-23T06:35:28.617 回答
0

万一其他人遇到此问题,修补该SysTrayIcon.shutdown方法就是为我解决的问题。

from infi.systray import SysTrayIcon
from infi.systray.traybar import PostMessage, WM_CLOSE


# Remove the thread.join from the SysTrayIcon.shutdown function
def custom_shutdown(self):
    if not self._hwnd:
        return      # not started
    PostMessage(self._hwnd, WM_CLOSE, 0, 0)
    #self._message_loop_thread.join()

# Overwrite shutdown function
SysTrayIcon.shutdown = custom_shutdown

# Use it as normal
sys_tray.shutdown()

我不确定为什么会发生这个问题。在我的情况下,我有在SysTrayIcon对象生命周期内创建和完成的守护进程,但在它们被创建之前我可以SysTrayIcon._message_loop_function.join()成功MainThread,但在我不能......

无论如何,简单地PostMessage(self._hwnd, WM_CLOSE, 0, 0)单独打电话似乎也有效。

于 2021-07-13T12:15:26.920 回答