python - Pyinstaller:无法创建具有 .png 文件的 onefile .exe
问题描述
我正在创建一个 tkinter 程序,我需要将其制作成 exe,以便将其发送给我的朋友。所以对于这个程序,我需要添加一个 .png 和 .ico 文件。这是我在 pyinstaller 中输入的用于安装 exe 的代码
pyinstaller .\u.py -F --noconsole --add-data 'C:\Users\Binoy\Desktop\Techwiz\h.png; .' -i ".\h.ico"
这是我的 .spec 文件:
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['U.py'],
pathex=['C:\\Users\\Binoy\\Desktop\\New folder'],
binaries=[],
datas=[('C:\\Users\\Binoy\\Desktop\\Techwiz\\h.png', '.')],
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='U',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=False , icon='h.ico')
我也有一个 .txt 文件,说明缺少模块,但在 .txt 中,他们说这些模块不会影响 .exe,所以我不在乎。起初它运行没有任何问题,但如果我删除.png 或者如果我的一位朋友下载它,它会显示错误Failed to execute script U
。所以我尝试了该resource_path()
功能(Pyinstaller 和 --onefile:如何在 exe 文件中包含图像),但没有奏效。所以我创建了一个 .bat 文件(保留由 Pyinstaller 创建的 exe 文件的错误消息),并得到了这个错误:
Traceback (most recent call last):
File "U.py", line 19, in <module>
File "tkinter\__init__.py", line 4062, in __init__
File "tkinter\__init__.py", line 4007, in __init__
_tkinter.TclError: couldn't open "C:/Users/Binoy/Desktop/Techwiz/h.png": no such file or directory
[8736] Failed to execute script U
有没有办法将带有 .exe 文件的图像(.png)存储为单个 .exe 文件?
解决方案
Joran Beasley 的评论是正确的。您的路径设置可能存在一些问题。如果我想编译一个包含外部文件的可执行文件,我使用以下方法
from PIL import Image
import os
import sys
#check if its a compiled exe
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
filePath = os.path.join(sys._MEIPASS, "test_picture.png")
#otherwise it must be a script
else:
scriptPath = os.path.realpath(os.path.dirname(sys.argv[0]))
filePath = os.path.join(scriptPath, "test_picture.png")
f = Image.open(filePath).show()
在此示例中,如果将其作为 .py 文件运行,则“test_picture”将与脚本相关。否则,它将存储在临时 _MEI 文件夹中。后者是通过定义的
datas = [...]
你已经在你的规范文件中做了。
此外,如果您运行 pyinstaller 可执行文件,您可能需要检查以下路径。
C:\用户...\AppData\Local\Temp\
应该有一个名为 _MEI 的文件夹,后跟一些数字。这是您的可执行文件将被提取的文件夹,以及您包含的所有数据
也可以看看
https://pyinstaller.readthedocs.io/en/stable/runtime-information.html
推荐阅读
- html - 检查器窗口的 html 中的 ::marker 是什么意思?
- linux - 如何使用终端删除mac中子文件夹下的常用文件
- react-native - Expo React Native:Strava 身份验证进入网站
- rspec - 将 ruby 更新到 2.7.1 后,rspec 测试抛出错误`Bundler::GemfileError for status code 4 but Bundler::GemfileError is already registered`
- c# - 创建通用 Linq 扩展方法以通过键“缝合”数据
- javascript - 获取数据或任何获取身份验证数据的方法
- swift - 从父视图SwiftUI访问子视图中的@State变量
- firebase - 组织多个 Firebase 应用程序共享数据库的最佳方式,并通过单独的身份验证
- python - 使用 Python 将文件从 S3 上传到 FTP 位置
- c++ - OpenGL 为计算着色器设置 SSBO