我正在写一个tkinter程序,它使用一些JPG文件作为背景。但是,我发现当脚本被转换成一个.exe文件使用“pyinstaller”时,用于tkinter窗口的映像不会被编译/添加到.exe文件中。在
因此,我决定在Python脚本中硬编码图像,这样就没有外部依赖性。为此,我做了以下几件事:
import base64
base64_encodedString= ''' b'hAnNH65gHSJ ......(continues...) '''
datas= base64.b64decode(base64_encodedString)
上述代码用于解码base64编码的图像数据。 我想用这个解码后的图像数据作为图片,并在tkinter中显示为标签/按钮。在
例如:
^{pr2}$但是,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
为了纠正ju 4321的正确答案,
PhotoImage
的正确行是:以及我的解决方案,即写入“image”字符串以便在以下时间后导入它:
^{2}$一个简单的
import image as img
和图像数据将使用Pyinstaller(-F
选项)存储在.exe文件中。在Tkinter
PhotoImage
类(在Python3和TK8.6中)只能读取GIF、PGM/PPM和PNG图像格式。有两种读取图像的方法:PhotoImage(file="path/to/image.png")
PhotoImage(data=image_data_base64_encoded_string)
首先,如果要将图像转换为base64编码的字符串:
然后在Tkinter中使用它:
^{2}$我认为您的问题是在使用
datas= base64.b64decode(base64_encodedString)
之前先用datas= base64.b64decode(base64_encodedString)
对字符串进行解码,而您应该直接使用base64_encodedString
。在相关问题 更多 >
编程相关推荐