[英]how to display an image in tkinter from a byte array
我从 web 中抓取了一些带有 aiohttp 的图片,然后我将它们保存在一个充满 arrays 的列表中('\xe25\xd7\xeeP{\x08\x18-6\x809\xabQ1Lx1\xf9\xabQ1Lx1\xf9 .\xc8...')
我正在尝试使用 canvas 和 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 class:
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)
有一种解决方法,但不是很好:您可以将每个图像保存为 jpg,然后使用 PIL 重新打开,然后使用 Photoimage 显示,但这需要 python 程序来保存图像。 我这样保存它们:
with open(r"example.jpg", 'wb') as f:
f.write(list_arrays[0])
然后使用 PhotoImage 显示该图像:
root = tk.Tk()
image = PIL.Image.open("example.jpg")
photo = PIL.ImageTk.PhotoImage(image)
ttk.Label(root,image=photo).pack()
root.mainloop()
这不是一个解决方案,而是一种解决方法,但我希望它有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.