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

PyInstaller打包含tksvg的Tkinter应用无法读取临时目录SVG文件

PyInstaller打包含tksvg的Tkinter应用时路径错误问题

我用Tkinter开发了一个桌面应用,需要借助tksvg库展示SVG文件。流程是先将SVG内容写入临时目录(实际写入逻辑比示例复杂),再在界面中展示。未打包时程序运行完全正常,但用PyInstaller打包成exe后,控制台报错找不到目标文件,路径末尾会自动追加\tksvg,而这个目录实际并不存在。看起来tksvg内部会创建这类子目录,但PyInstaller打包时可能缺少相关配置?我是纯新手,求指点解决办法。

最小复现代码

from tkinter import *
import tempfile
import tksvg

root = Tk()

temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
with open(temp_dir.name + f'\\test.svg', 'w') as a_file:
    a_file.write('<svg viewBox="0 0 400 400"><rect x="0" y="0" width="400" height="400"    fill="red" /></svg>')

svg_image = tksvg.SvgImage(file=temp_dir.name + f'\\test.svg')
show_svg = Label(root, image=svg_image)
show_svg.pack()


mainloop()

补充排查信息

我已确认问题出在PyInstaller对tksvg库的打包方式上。@JRiggles提出的方法本身有效,但不适用于tksvg对象,且我的场景不需要该方法(我通过临时目录管理文件)。为验证临时目录在PyInstaller打包后的可用性,我制作了一个JPEG查看器脚本,使用PIL库能正常读取临时目录中的JPEG文件,说明临时目录本身不存在问题。

JPEG查看器测试代码

from tkinter import *
import tempfile
from tkinter import filedialog
from PIL import Image, ImageTk

root = Tk()


temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)  # 验证临时目录是否创建

jpeg_file = filedialog.askopenfilename(filetypes=[("jpeg file", "*.jpeg")])  # 从磁盘选择文件
picture = Image.open(jpeg_file)  # 用PIL读取文件
picture.save(temp_dir.name+'\\test.jpeg')  # 将图片保存到临时目录

an_image = Image.open(temp_dir.name + '\\test.jpeg')  # 从临时目录读取图片
the_image = ImageTk.PhotoImage(an_image)  # 转换为Tkinter可用的图片格式

show_image = Label(root, image=the_image)  # 设置用于显示的标签
show_image.pack()  # 展示图片


mainloop()

有没有人有打包tksvg这类SVG库成exe的经验?求可行的解决方案。

内容的提问来源于stack exchange,提问作者Michał Lach

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:55:16