使用PyInstaller打包CustomTkinter程序时--add-data参数报错求助
解决PyInstaller打包CustomTkinter主题文件缺失问题
问题原因
你最后一个--add-data参数格式错误,PyInstaller要求每个--add-data必须明确指定源路径和目标路径的映射关系(Windows系统用分号分隔),你只写了源文件路径,没指定目标位置,所以触发报错。
方案1:修正--add-data参数格式
补充green.json的目标路径,确保它被放到打包后对应CustomTkinter的主题目录下:
pyinstaller --noconfirm --name Pendu --onedir --icon=icon.ico ^ --add-data "C:\Users\adamc\OneDrive\onda\envs\converter\Lib\site-packages\customtkinter;./customtkinter" ^ --add-data "C:\Users\adamc\OneDrive\onda\envs\converter\Lib\site-packages\customtkinter\assets\themes\green.json;./customtkinter/assets/themes/" ^ test.pyw
注:Windows下命令换行用
^,单行命令可直接省略^拼接。
方案2:打包整个themes文件夹更省心
没必要单独添加单个主题文件,直接打包整个themes文件夹,一次性解决所有主题文件缺失问题:
pyinstaller --noconfirm --name Pendu --onedir --icon=icon.ico ^ --add-data "C:\Users\adamc\OneDrive\onda\envs\converter\Lib\site-packages\customtkinter;./customtkinter" ^ --add-data "C:\Users\adamc\OneDrive\onda\envs\converter\Lib\site-packages\customtkinter\assets\themes;./customtkinter/assets/themes" ^ test.pyw
方案3:修改代码适配PyInstaller资源路径(推荐)
如果后续换主题或打包成--onefile格式,硬编码路径容易出问题,建议在代码里动态获取资源路径:
import sys import os import customtkinter def get_resource_path(relative_path): # 处理PyInstaller打包后的临时路径 if hasattr(sys, '_MEIPASS'): return os.path.join(sys._MEIPASS, relative_path) # 未打包时的本地路径 return os.path.join(os.path.abspath("."), relative_path) # 动态设置CustomTkinter主题路径 customtkinter.set_default_color_theme(get_resource_path("customtkinter/assets/themes/green.json"))
之后打包时只需添加整个customtkinter目录即可,命令同方案2,这种方式适配onedir和onefile两种打包模式,兼容性更强。
内容的提问来源于stack exchange,提问作者Adam Callet
相关产品推荐
相关产品推荐

