You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyInstaller编译Python代码后pystray无法运行,报AssertionError如何解决?

解决PyInstaller编译后pystray托盘图标失效问题

问题描述

Python代码运行时pystray托盘功能正常,但通过PyInstaller编译后功能失效,出现以下报错:

Traceback (most recent call last):
  File "pystray/_xorg.py", line 162, in _update_icon
  File "pystray/_xorg.py", line 395, in _assert_docked
AssertionError
Failed to dock icon
Traceback (most recent call last):
  File "pystray/_xorg.py", line 143, in _show
  File "pystray/_xorg.py", line 395, in _assert_docked
AssertionError

相关代码片段:

import pystray
from pystray import MenuItem as item

def create_tray():
    icon_image = Image.open("icon.png")
    tray_menu = (item('Show', lambda: show_app()), item('Quit', lambda: quit_program()))
    tray_icon = pystray.Icon("EasyLinux", icon_image, menu=pystray.Menu(*tray_menu))
    threading.Thread(target=tray_icon.run, daemon=True).start()

create_tray()

解决方案

1. 修复资源文件路径问题

PyInstaller编译后,原相对路径无法访问资源文件,需通过sys._MEIPASS获取临时资源目录:

import sys
import os
from PIL import Image

def get_resource_path(relative_path):
    try:
        base_path = sys._MEIPASS  # 打包后临时资源目录
    except Exception:
        base_path = os.path.abspath(".")  # 开发环境本地路径
    return os.path.join(base_path, relative_path)

# 修改create_tray中的图标加载逻辑
def create_tray():
    icon_image = Image.open(get_resource_path("icon.png"))
    tray_menu = (item('Show', lambda: show_app()), item('Quit', lambda: quit_program()))
    tray_icon = pystray.Icon("EasyLinux", icon_image, menu=pystray.Menu(*tray_menu))
    threading.Thread(target=tray_icon.run, daemon=True).start()

2. 打包时强制包含图标资源

执行PyInstaller命令时,通过--add-data参数将图标文件加入打包资源:

  • Linux/macOS环境:
    pyinstaller --onefile --add-data "icon.png:." your_script.py
    
  • Windows环境:
    pyinstaller --onefile --add-data "icon.png;." your_script.py
    

3. 调整托盘线程运行方式

守护线程可能在主线程退出后被强制终止,导致托盘图标无法正常驻留:

  • 若程序无需前台界面,直接在主线程运行托盘:
    def create_tray():
        # ... 其他代码不变
        tray_icon.run()  # 阻塞主线程,保持托盘活跃
    
  • 若需要后台运行,需确保主线程保持活跃:
    import time
    
    create_tray()
    while True:
        time.sleep(1)  # 主线程循环,防止程序退出
    

4. Xorg环境额外适配

报错来自X11相关模块,可尝试:

  • 打包时添加--windowed参数隐藏控制台,避免干扰托盘服务:
    pyinstaller --onefile --windowed --add-data "icon.png:." your_script.py
    
  • 确保系统已安装托盘指示器扩展(如GNOME桌面需安装gnome-shell-extension-appindicator)

内容的提问来源于stack exchange,提问作者YahyaMert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 23:51:12