问题描述
我在我的 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:Python34lib kinter\__init__.py", line 2609, in __init__ Widget.__init__(self, master, 'label', cnf, kw)
File "C:Python34lib kinter\__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
AAAAACH5BAEAAAIALAAAAAAQABAAQAQ3UMgpAKC4hm13uJnWgR
TgceZJllw4pd2Xpagq0WfeYrD7
2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7
'''
root = tk.Tk()
image = tk.PhotoImage(data=IMAGE_DATA)
label = tk.Label(root, image=image, padx=20, pady=20)
label.pack()
root.mainloop()
这篇关于Base64 字符串到 tkinter 中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)