在tkinter中将Base64字符串转换为图像
我在GUI中有一个正在使用的图像,当我编译.exe或.py时,我不希望它作为外部资源.我认为我应该将其编码为字符串,将字符串复制到代码中并进行解码,然后将其提供给Tkinter.尝试了很多解决方案,但仍然无法正常工作,下面是代码:
I have a image i'm using in my GUI and i dont want it as an external resource when i compile the .exe or to my .py. I figured i should encode it to a string, copy the string in the code and decode it and serve it to Tkinter. Tried a bunch of solutions but still doesnt work, here is the code:
import tkinter as tk
from tkinter import filedialog
from tkinter import *
import PIL
from PIL import Image, ImageTk
import base64
stringimagine="something the print gave me"
imagine=open('logo.jpg','rb')
encoded=base64.b64encode(imagine.read())
print(encoded)
imagine2=base64.b64decode(stringimagine)
fereastra_principala = tk.Tk()
poza=Label(fereastra_principala,image=imagine2)
poza.pack(fill='both',expand='yes')
fereastra_principala.mainloop()
对于此代码,我收到此错误:
to this code i receive this error:
File "C:\Python34\lib\tkinter\__init__.py", line 2609, in __init__ Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2127, in __init__ (widgetName, self._w) + extra + self._options(cnf))_tkinter.TclError
这就是我现在用来获取照片的方式,作为外部资源:
And this is how i use to get the photo now, as an external resource:
img=Image.open('logo.jpg')
image=ImageTk.PhotoImage(img)
poza=Label(fereastra_principala,image=image)
poza.pack()
如果具有base64编码的数据,则需要使用 data
参数.但是,我认为这不适用于jpg.它将适用于.gif图像.
If you have base64-encoded data, you need to use the data
argument. However, I don't think this will work for jpg. It will work for .gif images though.
这就是规范文档所说的数据选项:
This is what the canonical documentation says for the data option:
将图像的内容指定为字符串.该字符串应包含二进制数据,或者对于某些格式,应包含base64编码的数据(目前保证GIF图像支持该数据).字符串的格式必须是其中一种具有可接受字符串数据的图像文件格式处理程序的格式.如果同时指定了-data和-file选项,则-file选项优先.
Specifies the contents of the image as a string. The string should contain binary data or, for some formats, base64-encoded data (this is currently guaranteed to be supported for GIF images). The format of the string must be one of those for which there is an image file format handler that will accept string data. If both the -data and -file options are specified, the -file option takes precedence.
示例
import Tkinter as tk
IMAGE_DATA = '''
R0lGODlhEAAQALMAAAAAAP//AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAA\nAAAAACH5BAEAAAIALAAAAAAQABAAQAQ3UMgpAKC4hm13uJnWgR
TgceZJllw4pd2Xpagq0WfeYrD7\n2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7\n
'''
root = tk.Tk()
image = tk.PhotoImage(data=IMAGE_DATA)
label = tk.Label(root, image=image, padx=20, pady=20)
label.pack()
root.mainloop()