Pyinstaller 将图像放在单独的文件问题上?我该如何解决?

Pyinstaller Placing Images On Separate File Problem? How Do I Fix This?

我试图将我的图像放在一个单独的文件中,然后放在我的 exe 文件中,因为 我有很多图像,我不希望滚动的人抛出数千张图像只是为了找到exe

I dont know if I am missing something on my .spec

这就是我所做的,我为我的图像创建了一个文件夹并添加了它们,然后 exe 位于我的图像文件夹之外,但发生的事情是它没有检测到该文件夹​​中的图像 *我搞砸了我的 .spec 文件上有什么东西?


# -*- mode: python ; coding: utf-8 -*-

block_cipher = None


a = Analysis(['tower.py'],
             pathex=['C:\Users\Habib\Desktop\AllMyGames\TowerD'],
             binaries=[],
             datas=['C:\Users\Habib\Desktop\AllMyGames\TowerD\dist\image'],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='tower',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False )


它最终只会说

FAILED TO EXECUTE SCRIPT 

我看到两个问题:

  1. 您的 datas 字符串包含反斜杠(python 字符串的转义字符),导致路径字符串无效。
  2. datas 属性 的结构不正确。

来自文档:

The list of data files is a list of tuples. Each tuple has two values, both of which must be strings:

  • The first string specifies the file or files as they are in this system now.
  • The second specifies the name of the folder to contain the files at run-time.

https://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-data-files

因此,假设您的项目根目录是 C:\Users\Habib\Desktop\AllMyGames\TowerD,更改

# Change this line
datas=['C:\Users\Habib\Desktop\AllMyGames\TowerD\dist\image']
# To this
datas=[('dist/image', 'image')]

而且我认为它会起作用。

我建议您检查您的图片是否为 ico 格式,如果不是 使用 :https://icoconvert.com 如果这仍然不起作用,请重新执行该过程,但在您的 cmd 提示符下写入 'pyinstaller -icon "Your .ico file" and your project.py'

正如@Multihunter 所说,路径未转义,因此脚本失败,这是最简单的解决方案

替换

datas=['C:\Users\Habib\Desktop\AllMyGames\TowerD\dist\image']

datas=[r'C:\Users\Habib\Desktop\AllMyGames\TowerD\dist\image']

在您的字符串前加上 r 不会转义任何字符,您的路径将如您所愿。

参考this