pyinstaller 打包时关于加载资源文件

2023天前 · 分享 · python · 1428次阅读

今天跟着书写完整了一个小游戏demo,然后想做个单独的exe,不过问题是py文件中加载本地图片但pyinstaller是不打包的。

准确说是要手动添加下才行。

pyinstaller -F -i=my.ico -w yourmain.py

先通过此步生成spec文件,然后做出下面的修改:

# -*- mode: python -*-

block_cipher = None

added_files = [
('images/alien.bmp','.'),
('images/ship.bmp','.')
]

a = Analysis(['alien_invasion.py'],
             pathex=['C:\\xxx\\alien_invasion'],
             binaries=[],
             datas = added_files,
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
extra_tree = Tree('./images', prefix = '.')
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='alien_invasion',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=False )

其中

added_files = [
('images/alien.bmp','.'),
('images/ship.bmp','.')
]

这里是添加资源文件,前面是相对路径,当然也可以写绝对路径,后面是在打包好的程序中的“路径”,一个点即根目录。

datas = added_files

这里就不用多说了,这样写比较直观,你要想合并在一起也是可以的。

extra_tree = Tree('./images', prefix = '.')

这里前者是打包前的资源文件路径,后面的点和上面一致(不是很确定)

在重新打包前,如果代码中有对路径文件的操作,需要通过一个函数确定其在程序包中的“路径”
函数如下(记得import os和sys两个包):

def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

最后再次执行

pyinstaller -F -i=my.ico yourmain.spec

就OK了,这个时候exe就能完整独立运行了

参考链接:
https://loserfer.blogspot.com/2018/04/pyinstaller.html

👍 0

none

最后修改于2023天前

评论

贴吧 狗头 原神 小黄脸
收起

贴吧

狗头

原神

小黄脸

目录

avatar

未末

迷失

126

文章数

275

评论数

7

分类