【问题标题】:Base64 string to image in tkinterBase64 字符串到 tkinter 中的图像
【发布时间】:2017-03-16 12:53:00
【问题描述】:

我在我的 GUI 中使用了一个图像,当我编译 .exe 或我的 .py 时,我不希望它作为外部资源。 我想我应该将它编码为一个字符串,复制代码中的字符串并对其进行解码并将其提供给 Tkinter。试了很多办法还是不行,代码如下:

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()

【问题讨论】:

    标签: python string tkinter base64 encode


    【解决方案1】:

    如果您有 base64 编码的数据,则需要使用 data 参数。但是,我认为这不适用于 jpg。不过,它适用于 .gif 图像。

    这是canonical documentation 对数据选项所说的:

    将图像的内容指定为字符串。字符串应该包含二进制数据,或者对于某些格式,base64 编码的数据(目前保证支持 GIF 图像)。字符串的格式必须是其中有一个将接受字符串数据的图像文件格式处理程序的格式之一。如果同时指定了 -data 和 -file 选项,则 -file 选项优先。

    示例

    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()
    

    【讨论】:

    • 您好,感谢您的回答。我不一定要在 base64 中加密它,但这是我找到的方法。它必须是 .jpg,因为如果我将其转换为 gif,质量就是垃圾,我打算将其用作徽标。如果您知道除了 base64 加密之外的任何其他方式,请告诉。
    【解决方案2】:

    有办法:

    说image='abc'是b64编码的图片字符串。

    def install():
        if not os.path.isfile("logo.jpg"):
            open('logo.jpg','wb').write(base64.b64decode(image))
    

    将在我的 main() 函数中运行它,如果图像不存在于文件夹中,它将被创建。之后,您将照常加载图像:

    self.img=Image.open('logo.jpg')
    self.image=ImageTk.PhotoImage(self.img)
    

    但是,我还没有找到根本不保存图像的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2017-06-29
      • 2019-04-11
      相关资源
      最近更新 更多