如何在 Tkinter 标签中使用 base64 编码的图像字符串?

How do I use the base64 encoded image string in Tkinter label?

我正在编写一个使用一些 JPG 文件作为背景的 tkinter 程序。但是,我发现当使用 "pyinstaller" 将脚本转换为 .exe 文件时,用于 tkinter windows 的图像不是 compiled/added 到 .exe 文件。

因此,我决定在 Python 脚本中对图像进行硬编码,这样就没有外部依赖性了。为此,我做了以下事情:

import base64
base64_encodedString= ''' b'hAnNH65gHSJ ......(continues...) '''
datas= base64.b64decode(base64_encodedString)

以上代码用于解码base 64编码的Image数据。 我想使用此解码图像数据用作图片并在 tkinter 中显示为 label/button。

例如:

from tkinter import *
root=Tk()
l=Label(root,image=image=PhotoImage(data=datas)).pack()
root.mainloop()

但是,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

Tkinter PhotoImage class(在 Python 3 with tk 8.6 中)只能读取 GIF、PGM/PPM 和 PNG 图像格式。读取图片有两种方式:

  • 来自文件:PhotoImage(file="path/to/image.png")
  • 来自 base64 编码的字符串:PhotoImage(data=image_data_base64_encoded_string)

首先,如果你想将图像转换成base64编码的字符串:

import base64

with open("path/to/image.png", "rb") as image_file:
    image_data_base64_encoded_string = base64.b64encode(image_file.read()) 

然后在Tkinter中使用它:

import tkinter as tk

root = tk.Tk()

im = tk.PhotoImage(data=image_data_base64_encoded_string)

tk.Label(root, image=im).pack()

root.mainloop()

我认为你的问题是你在 PhotoImage 中使用它之前用 datas= base64.b64decode(base64_encodedString) 解码了字符串,而你应该直接使用 base64_encodedString

只是为了更正 j_4321 的非常好的答案,PhotoImage 的正确行是:

im = tk.PhotoImage(data=image_data_base64_encoded_string)

我的解决方案是编写 'image' 字符串以便在 :

之后导入它
with open("image.py", "wb") as fichier:
    fichier.write(b'imageData=b\'' + image_data_base64_encoded_string + b'\'')

一个简单的import image as img,图像数据将使用Pyinstaller(-F选项)存储在.exe文件中。