Python 将Base64字符串转换为tkinter中的图像
我在GUI中使用了一个图像,当我编译.exe或.py时,我不希望它作为外部资源。 我想我应该把它编码成一个字符串,在代码中复制这个字符串,然后解码,然后把它提供给Tkinter。尝试了一系列解决方案,但仍然无效,下面是代码:Python 将Base64字符串转换为tkinter中的图像,python,string,tkinter,base64,encode,Python,String,Tkinter,Base64,Encode,我在GUI中使用了一个图像,当我编译.exe或.py时,我不希望它作为外部资源。 我想我应该把它编码成一个字符串,在代码中复制这个字符串,然后解码,然后把它提供给Tkinter。尝试了一系列解决方案,但仍然无效,下面是代码: import tkinter as tk from tkinter import filedialog from tkinter import * import PIL from PIL import Image, ImageTk import base64 strin
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()
对于此代码,我收到以下错误:
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
这就是我现在作为外部资源获取照片的方式:
img=Image.open('logo.jpg')
image=ImageTk.PhotoImage(img)
poza=Label(fereastra_principala,image=image)
poza.pack()
如果您有base64编码的数据,则需要使用data参数。然而,我认为这对jpg不起作用。不过,它可以用于.gif图像 以下是数据选项的说明: 将图像的内容指定为字符串。该字符串应包含二进制数据,或者对于某些格式,应包含base64编码的数据。目前保证GIF图像支持这种格式。字符串的格式必须是具有接受字符串数据的图像文件格式处理程序的格式之一。如果同时指定了-data和-file选项,则-file选项优先 实例 将Tkinter作为tk导入 图像数据仓库 r0lgodlheaaqalmaaap//AP///waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA\naaaaach5baaaaaaaaaaaaaaaaaaq3umgpakc4hm13ujnwgr TgceZJllw4pd2Xpagq0WfeYrD7\n2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7\n ' root=tk.tk image=tk.PhotoImagedata=image\u数据 label=tk.Labelroot,image=image,padx=20,pady=20 label.pack root.mainloop 有办法: 假设image='abc'是b64中编码的图像字符串
def install():
if not os.path.isfile("logo.jpg"):
open('logo.jpg','wb').write(base64.b64decode(image))
我将在我的主功能中运行这个,如果该图像不存在于文件夹中,它将被创建。后记:您将按照正常方式加载图像:
self.img=Image.open('logo.jpg')
self.image=ImageTk.PhotoImage(self.img)
但是,我还没有找到一个根本不保存图像的解决方案。您好,谢谢您的回答。我不一定要在base64中加密它,但这是我找到的方法。它需要是一个.jpg,因为如果我把它转换成gif,它的质量就是垃圾,我打算把它用作一个徽标。如果您知道base64加密以外的任何其他方法,请告诉我。