python - Pyinstaller 图像不加载

标签 python pygame pyinstaller cx-freeze

问题

我试图将 python 文件转换为 EXE 文件,但我似乎每次都遇到同样的问题,无论是 CX_Freeze 还是 Pyinstaller。我刚刚尝试使用 pyinstaller 并使用命令制作了一个 EXE 文件

pyinstaller --onefile thepyfile

一切正常。它在 dist 文件中创建 exe。但是,当我打开 exe 时,它​​会显示一个命令窗口,然后迅速关闭。我设法捕获了我使用打印屏幕时遇到的错误,它说 pygame 错误:无法打开图像 family.jpg。我正在使用 pygame 模块。

我尝试了什么?

我确保图像与我的 python 文件位于同一目录和同一文件夹中。当我运行它时,我的 .py 工作正常,它只是 exe。无论如何,只是为了确保在我使用

加入路径的路径中加载图像没有问题
os.path.join

它再次适用于 py 文件,但它不适用于 exe。我还检查了我是否正确安装了pyinstaller,它适用于其他不涉及导入图像的exe程序。我也确实尝试创建一个文件夹然后使用

os.path.join(folder,file)

但它再次在 py 文件中起作用,但在 pyinstaller/cx_freeze exe 中不起作用。

线索?

当我使用 CX__freeze 时,我发现 pygame 也无法导入图像。但是它给了我一个更大的错误案例,不确定它是否有用但是,它可能是一个线索?

enter image description here

请帮忙

我现在已经遇到这个问题超过 5 个星期了,我迫切需要帮助。

一些代码

这就是我导入图像的方式(同样适用于 py 文件,但不适用于 exe)

family_image = pygame.image.load(os.path.join('folder',"family.jpg")).convert()

如果需要,这里是我的 cx_Freeze setup.py,它也制作 exe 文件,但给我图像无法加载错误。

import cx_Freeze
import sys
import pygame
import random
import math
import os
os.environ['TCL_LIBRARY'] = "C:\\Program Files\\Python35\\tcl\\tc18.6"
os.environ['TK_LIBRARY'] = "C:\\Program Files\\Python35\\tcl\\tk8.6"


base = None

if sys.platform == 'win32':
    base = "Win32GUI"





executables = [cx_Freeze.Executable("Treg&Shelly.py",shortcutName="Cards",shortcutDir="DesktopFolder",base = base)]

cx_Freeze.setup(
    name = "HAPPY NEW YEARS",
    options = {"build_exe":{"packages":["pygame","random","math"],"excludes" : ['tcl','ttk','tkinter','Tkinter'],"include_files":["family.jpg","newyears.png"]}},
    version = "0.01",
    description = "New Years Card",
    executables = executables

    )

注意

我所有的图像都在一个单独的文件夹中,但可以通过我的 python 文件访问。

我也在使用 python 3.5

感谢您的任何回复

最佳答案

如果您创建一个文件夹 bundle (删除 --onefile 参数),pyinstaller 捆绑工作正常,那么问题可能是这样的:

当您运行单文件包时,会创建一个临时文件夹结构。临时文件夹的名称是在运行时创建的,捆绑时不知道。因此路径未知。

但是,Pyinstaller 添加了一个属性 sys._MEIPASS,其中包含临时文件夹的绝对路径。因此,请尝试类似的操作:

if getattr(sys, 'frozen', False):
    wd = sys._MEIPASS
else:
    wd = ''    
family_image = pygame.image.load(os.path.join(wd,'folder',"family.jpg")).convert()

另见 Pyinstaller docu .

关于python - Pyinstaller 图像不加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646891/

相关文章:

python - 找不到pygame

Python - 执行exe文件时出现pygame错误

python - 从右开始累计

python - Django 静态文件服务与 React Router 冲突

python - 如何在 python 中使用十六进制值而不是 RGB 值。 Python 2.7

python - 使用 pygame 在 Python 中通过按键加载图像

python - 使用 pyinstaller 经验制作的可执行文件 "Fatal python error: initfsencoding"

python - 在 PyInstaller 中,为什么 NumPy.Random.Common 不能作为模块加载?

python - 安装 distutils 包时如何使用 mingw32?

python - pandas:如何通过选择列范围来过滤行?