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

如何动态设置根目录?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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 05:45:39