如何动态设置根目录?EXE生成后字体路径访问异常问题
解决打包EXE后字体路径找不到的问题
1. 动态获取程序根目录
不管是本地运行脚本,还是打包成EXE后运行,都需要先拿到可靠的程序根路径,避免硬编码路径导致的适配问题:
import os import sys def get_root_path(): # 判断是否为PyInstaller打包后的环境 if getattr(sys, 'frozen', False): # 打包后,sys.executable指向EXE文件路径,取其所在目录作为根 root_path = os.path.dirname(os.path.abspath(sys.executable)) else: # 本地运行时,取当前脚本所在目录的父目录作为根(可根据项目结构调整) root_path = os.path.dirname(os.path.abspath(__file__)) return root_path
2. 重构路径配置
将所有路径改为基于动态获取的根路径构建,确保本地与打包后路径一致:
gv.root_path = get_root_path() gv.application_dir = os.path.join(gv.root_path, "application") gv.install_dir = os.path.join(gv.application_dir, "install") gv.modules_dir = os.path.join(gv.application_dir, "modules") gv.fi_dir = os.path.join(gv.application_dir, "icons") gv.itemmanage_dir = os.path.join(gv.modules_dir, "itemmanage") gv.assets_dir = os.path.join(gv.itemmanage_dir, "assets") gv.image_dir = os.path.join(gv.assets_dir, "images") gv.user_image_dir = os.path.join(gv.image_dir, "user") gv.depend_dir = os.path.join(gv.modules_dir, "dependancy") gv.depend_image_dir = os.path.join(gv.depend_dir, "images") gv.invoice_dir = os.path.join(gv.modules_dir, "invoices")
3. 确保字体文件被打包进EXE
用PyInstaller打包时,必须把FreeSerif.ttf纳入打包范围,两种实现方式:
- 命令行打包:添加参数指定资源文件,Windows用分号分隔路径,macOS/Linux用冒号:
pyinstaller --add-data "你的本地FreeSerif.ttf路径;application/install" 你的主脚本.py - 编辑.spec文件:在
datas字段中添加资源映射,再用.spec文件打包:
然后执行:datas=[('你的本地FreeSerif.ttf路径', 'application/install')],pyinstaller 你的脚本.spec
4. 字体加载代码保持不变
调整路径配置后,原有的字体加载代码可以直接使用,此时gv.install_dir已经是正确的动态路径:
inv_file = FPDF() inv_file.add_page() inv_file.set_xy(0, 0) inv_file.add_font("monaco", "", os.path.join(gv.install_dir,"FreeSerif.ttf"), uni=True)
内容的提问来源于stack exchange,提问作者Shafayat Mugdha
相关产品推荐
相关产品推荐

