首页 > 解决方案 > 如何在 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)

标签: pythonarraystkintertkinter-canvasphotoimage

解决方案


只要您提供文件格式,您就可以使用字节初始化 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)

推荐阅读