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

Bou*_*Dev 2 python base64 image tkinter pyinstaller

我正在编写一个使用一些 JPG 文件作为背景的 tkinter 程序。但是,我发现当使用“pyinstaller”将脚本转换为 .exe 文件时,用于 tkinter 窗口的图像不会被编译/添加到 .exe 文件中。

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

import base64
base64_encodedString= ''' b'hAnNH65gHSJ ......(continues...) '''
datas= base64.b64decode(base64_encodedString)
Run Code Online (Sandbox Code Playgroud)

以上代码用于对base 64编码的Image数据进行解码。我想将此解码后的图像数据用作图片并在 tkinter 中显示为标签/按钮。

例如:

from tkinter import *
root=Tk()
l=Label(root,image=image=PhotoImage(data=datas)).pack()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

但是,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
Run Code Online (Sandbox Code Playgroud)

j_4*_*321 7

TkinterPhotoImage类(在 Python 3 和 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()) 
Run Code Online (Sandbox Code Playgroud)

然后在 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()
Run Code Online (Sandbox Code Playgroud)

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