python - 如何在 tkinter 中从字节数组显示图像
问题描述
我从网上用 aiohttp 抓取了一些图片,并将它们保存在一个列表中,其中包含这样的数组('\xe25\xd7\xeeP{\x08\x18-6\x809\xabQ1LQ\xf0\x02hC\x11\x97* .\xc8...')
我正在尝试使用画布和 Photoimage 显示图片,但它不起作用
这是我的代码的一些片段,在此先感谢,对不起我的英语
bytesfoto=self.fotobytes[indice]
img = ImageTk.PhotoImage(Image.open(BytesIO(bytesfoto)))
self.canvas.create_image(20, 20, anchor=NW, image=img)
self.canvas = Canvas(width=300, height=300)
self.canvas.grid(row=2, column=1)
解决方案
只要您提供文件格式,您就可以使用字节初始化 Tkinter PhotoImage 类:
image_content = b'...' # Data you scraped from some URL
file_format = 'jpg' # The file extension of the sourced data
canvas = tk.Canvas(window, width=300, height=300)
canvas.pack()
img = tk.PhotoImage(data=image_content, format=file_format)
canvas.create_image(20, 20, anchor=tk.NW, image=img)
推荐阅读
- string - 如何在给定字符串中查找最大 As Substring 数
- java - SQL插入查询不按按钮存储
- python - 如果一个字段不存在,如何在 JSON 中跳过?
- javascript - 在 Google 表格中将报告发送到邮件
- api-platform.com - API 平台:按数量订购
- rust - 为什么使用 PhantomData
被添加到结构中,但代码仍然可以编译并且有一个 use-after-free 错误 - jestjs - 笑话:如何测试一个组件是否具有某个 ref 属性?
- firemonkey - 如何在 C++Builder 的任务中加载图像?
- asp.net-web-api - .Net Core 5:WebApi 查询字符串参数
- github - npm 版本,github,在版本提交时跳过 CI,但在合并时触发