Mobile wallpaper 1
259 字
1 分钟
CustomTkinter添加图标以及Pyinstaller打包
2025-12-19

CustomTkinter中添加图标#

# 设置窗口图标
# 获取图标文件路径(支持打包后从资源中读取)
icon_path = self.resource_path('icon.png')
try:
# 创建PhotoImage对象
self.iconpath = ImageTk.PhotoImage(file=icon_path)
# 先调用wm_iconbitmap进行初始化
self.root.wm_iconbitmap()
# 再设置iconphoto
self.root.iconphoto(False, self.iconpath)
except Exception as e:
# 如果无法加载图标,使用默认设置
print(f"设置图标时发生错误:{e}")

Pyinstaller打包#

打包单文件时,需要将icon.png一起打包

终端运行时添加 —add-data=“资源路径;打包里的路径”

pyinstaller --onefile--icon=favicon.ico --add-data="favicon.ico;." --add-data="icon.png;." main.py

.spec文件中 datas=[ ] 添加,左边是资源路径,右边是放入打包里的路径

datas=[('favicon.ico', '.'), ('icon.png', '.')],

在Pyinstaller打包机制中,运行打包的exe文件时,会将资源放到临时文件夹中

所以需要用到sys._MEIPASS访问临时文件夹

def resource_path(self, relative_path):
"""获取资源的绝对路径,用于支持PyInstaller打包后的资源访问"""
try:
# PyInstaller创建临时文件夹,并将路径存储在_MEIPASS中
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)

分享

如果这篇文章对你有帮助,欢迎分享给更多人!

CustomTkinter添加图标以及Pyinstaller打包
https://blog.nth2miss.cn/posts/customtkinter添加图标以及pyinstaller打包/
作者
Nth2Miss
发布于
2025-12-19
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00