是否可能在Python中包含图片数据?

2024-03-29 12:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,用Pyinstaller编译成一个.exe文件。不幸的是,脚本和编译的文件必须与我的.ico和背景(.png)图像在同一个目录中,正如我这样引用它们:

root.iconbitmap("logo.ico")
background = ImageTk.PhotoImage(Image.open("background.png"))

是否可以将图片数据包含在脚本文件本身中,而不是使其依赖于单个可执行文件之外的文件?我用的是Tkinter和PIL。在


Tags: 文件图像目录脚本pngrootexelogo
2条回答

按照建议,可以使用base64对其进行编码:

import base64

im_filename = 'background.png'
im_variableName = 'background'
py_filename = 'embeddedImage.py'

with open(im_filename,'rb') as f:
    str64 = base64.b64encode(f.read())

with open(py_filename,'w') as f:
    f.write('%s="%s"'%(im_variable_name,str64))

然后:

^{pr2}$

您可以在任何脚本中包含任何大小合理的文件,只需对其进行base64编码。然后将其存储为字符串。在

相关问题 更多 >