python - 使用Tkinter时如何解决Base64图像错误
问题描述
我想使用 tkinter 显示 base64 图像。我在 jupyter 笔记本上运行 python 3。
基于这个问题,我做了以下事情:
我导入 PNG 图像并将其转换为 base64 格式
我尝试使用 Tkinter 打开它
import base64 with open("IMAGE.png", "rb") as image_file: image_data_base64_encoded_string = base64.b64encode(image_file.read()) import tkinter as tk from PIL import ImageTk, Image root = tk.Tk() im = ImageTk.PhotoImage(data=image_data_base64_encoded_string) tk.Label(root, image=im).pack() root.mainloop()
我得到了错误:
OSError Traceback (most recent call last) <ipython-input-34-96dab6b5d11a> in <module>() 5 root = tk.Tk() 6 ----> 7 im = ImageTk.PhotoImage(data=image_data_base64_encoded_string) 8 9 tk.Label(root, image=im).pack() ~\Anaconda3\lib\site-packages\PIL\ImageTk.py in __init__(self, image, size, **kw) 92 # Tk compatibility: file or data 93 if image is None: ---> 94 image = _get_image_from_kw(kw) 95 96 if hasattr(image, "mode") and hasattr(image, "size"): ~\Anaconda3\lib\site-packages\PIL\ImageTk.py in _get_image_from_kw(kw) 62 source = BytesIO(kw.pop("data")) 63 if source: ---> 64 return Image.open(source) 65 66 ~\Anaconda3\lib\site-packages\PIL\Image.py in open(fp, mode) 2655 warnings.warn(message) 2656 raise IOError("cannot identify image file %r" -> 2657 % (filename if filename else fp)) 2658 2659 # OSError: cannot identify image file <_io.BytesIO object at 0x000001D476ACF8E0>
任何人都知道如何解决这个问题?
解决方案
看起来您链接到的问题使用了该类,该类与您的代码使用的tkinter.PhotoImage
类具有不同的接口。PIL.ImageTk.PhotoImage
后者接受一个普通的bytes
对象。您不需要先对其进行 base64 编码。
import base64
with open("IMAGE.png", "rb") as image_file:
image_data = image_file.read()
import tkinter as tk
from PIL import ImageTk, Image
root = tk.Tk()
im = ImageTk.PhotoImage(data=image_data)
tk.Label(root, image=im).pack()
root.mainloop()
或者,继续对您的数据进行 base64 编码,但使用tkinter.PhotoImage
.
import base64
with open("IMAGE.png", "rb") as image_file:
image_data_base64_encoded_string = base64.b64encode(image_file.read())
import tkinter as tk
from PIL import Image
root = tk.Tk()
im = tk.PhotoImage(data=image_data_base64_encoded_string)
tk.Label(root, image=im).pack()
root.mainloop()
推荐阅读
- trading - 为多交叉条件检查存储交叉值 Pine 脚本
- javascript - 合并具有相同键的对象数组
- python - 谁能解释为什么“二”>“七十亿”等于真?
- html - 如何将无法调整的表格放入 Google Web Designer?
- javascript - 如何使用 CSVLink 下载所有行?
- android - 使用jetpack compose的Android滑动动画
- wordpress - wp-nav-menu 生成一个空的 a 标签
- python - 无法使用 python 连接到已经打开的 SAP GUI 会话
- entity-framework-core - 为什么我不能使用 EF Core 在现有数据库中创建新表?(代码优先)
- ios - 发布版本的 module.modulemap 中缺少 Foo-Swift.h