tkinter 无法识别图像数据

tkinter couldn't recognize image data

我想使用存储在 JSON 文件中的 base64 字符串在 tkinter.Label 中显示 jpg 图像,但出现以下错误: _tkinter.TclError: 无法识别图像数据

这是我的代码块:

import json
import base64
import tkinter as tk

image_data = {}
def image_to_json():
    with open("path/to/image.jpg","rb") as image:
        data = base64.b64encode(image.read())
        image_data["data"]=str(data)
    with open("jsonfile.json", "w") as file:
        json.dump(image_data, file)

def json_to_image():
    with open("jsonfile.json", "rb") as file:
        contents = json.load(file)
        img_data = contents["data"]
        return img_data

if __name__=="__main__": 
    root = tk.Tk()
    image_to_json()
    converted_image = tk.PhotoImage(data=json_to_image())
    label = tk.Label(root, image = converted_image).pack()
    root.mainloop

我也尝试过使用 png 文件并得到同样的错误

您可能需要正确解码字符串:

已编辑试试这个:

image_data = {}
with open("path/to/image.png", "rb") as image:
    data = base64.encodebytes(image.read())#
    data = data.decode("utf-8")
    image_data["data"] = data
    
    
with open("jsonfile.json", "w") as file:
    json.dump(image_data, file)

with open("jsonfile.json", "rb") as file:
    contents = json.load(file)
    image_data = contents["data"]

然后就可以了:

root = tk.Tk()
converted_image = tk.PhotoImage(data=image_data)
label = tk.Label(root, image = converted_image).pack()
root.mainloop()