我已经从 python tkinter GUI 成功创建了一个包含图像的 EXE 文件。请参阅以下代码:
lblLogo=Label(main)
lblLogo.grid(row=3,column=11,rowspan=4)
try:
filelocation="C:/Documents/Python/ScreenPartNumberProgram/"
KasonLogo=PhotoImage(file=filelocation+"KasonLogo.png")
KasonLogo=KasonLogo.zoom(25,20)
KasonLogo=KasonLogo.subsample(50,50)
lblLogo.config(image=KasonLogo)
icon=PhotoImage(file=filelocation+"KasonLogo.png")
main.tk.call('wm','iconphoto',main._w,icon)
except:
print("warning: could not load photos")
lblLogo.config(text="[KasonLogo.png]")
exe 文件在我的计算机上打开并完美运行。我使用此命令来获取 .exe:
pyinstaller --onefile --noconsole myscript.py
唯一的问题是该文件要求图像位于同一文件夹中,否则不会显示在标签上。如何在不需要外部文件的情况下将图像捆绑到 EXE 中?
提前致谢
编辑: 我查看了提供的链接,做了更多研究,但仍然没有解决问题。仅当图像位于同一文件夹中时该程序才有效。我真的很想让它在不需要外部图像文件的情况下工作。 resources_path 技术似乎也不适合我......
我还尝试修改我的代码以使用 PIL 的 ImageTk 和同样的问题。仅当外部图像文件位于其文件夹中时,程序才会加载图像。
最佳答案
天哪!经过几天的头痛之后,我终于找到了一种有效的方法...这是我为使程序在不需要外部图像文件的情况下工作而所做的:
第1步:对图像文件进行编码(注意必须是GIF,可以使用paint进行转换):
import base64
with open("MyPicture.gif", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
print(encoded_string)#print string to copy it (see step 2)
第 2 步:下一步是将字符串复制并粘贴到单独的 myimages.py 文件中,然后 将其存储为变量。例如:
imageString = b'R0lGODlhyADIAPcAAAA .....blah blah really long string.......'
第3步:然后将myimages.py导入主程序并调用变量
from myimages import *
pic=imageString#GIF decoded to string. imageString from myimages.py
render = PhotoImage(data=pic)
myLabel.config(image=render)
第 4 步:在规范文件中:包含 myimages.py 作为数据
# -*- mode: python -*-
block_cipher = None
#instructions: pyinstaller --onefile --noconsole myProgram.spec
file_name = 'myProgram'
add_files=[('myimages.py','module')]
a = Analysis([file_name+'.py'],
pathex=['C:\\Program Files (x86)\\Python36-32\\Scripts'],
binaries=[],
datas=add_files,
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=exclude_list,
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name=file_name,
debug=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=False )
第5步:最后可以编译为EXE:
pyinstaller --onefile --noconsole myProgram.spec
叹息如果有人有更好的解决方案,请在此处发布。直到那时我很高兴有些东西起作用了......
关于python pyinstaller 将 GUI 中的图像捆绑到 onefile EXE 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48134269/