我正在编写一个tkinter程序,其中利用了一些JPG文件作为背景。但是,我发现当使用“pyinstaller”将脚本转换为.exe文件时,用于tkinter窗口的图片未被编译/添加到.exe文件中。
因此,我决定在Python脚本中硬编码图像,以便没有外部依赖关系。为此,我已经完成了以下工作:
上面的代码用于解码base64编码的图像数据。 我想使用这个解码后的图片数据作为tkinter标签/按钮中的图片显示。 例如:
然而,tkinter不接受存储在
因此,我决定在Python脚本中硬编码图像,以便没有外部依赖关系。为此,我已经完成了以下工作:
import base64
base64_encodedString= ''' b'hAnNH65gHSJ ......(continues...) '''
datas= base64.b64decode(base64_encodedString)
上面的代码用于解码base64编码的图像数据。 我想使用这个解码后的图片数据作为tkinter标签/按钮中的图片显示。 例如:
from tkinter import *
root=Tk()
l=Label(root,image=image=PhotoImage(data=datas)).pack()
root.mainloop()
然而,tkinter不接受存储在
data
中的值作为图像使用。它显示以下错误 -Traceback (most recent call last):
File "test.py", line 23, in <module>
l=Label(root,image=PhotoImage(data=datas))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3394, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3350, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize image data
.gif
和.png
格式都可以正常工作。因此问题在于你的背景图片是JPG
格式,而 Tkinter 不支持该格式。尝试将你的图片转换为PNG
或GIF
格式,然后它应该可以正常工作。 - j_4321