[英]Load image from BytesIO object to Tk widget
I want to render an image from a BytesIO object to a canvas for this I'm using this code: 我想为此将图像从BytesIO对象渲染到画布上:
from io import BytesIO
from Tkinter import *
from PIL import Image as ImageModule
f = open("test.png","rb")
bdata = BytesIO()
bdata.write(f.read())
bdata.seek(0)
pilImage = ImageModule.open(bdata)
canvas_width = 794
canvas_height =559
master = Tk()
canvas = Canvas(master,
width=canvas_width,
height=canvas_height)
canvas.pack()
img = PhotoImage(pilImage)
i = canvas.create_image(0,0, anchor=NW, image=img)
mainloop()
I got this error message with canvas and labels: 我收到了带有画布和标签的错误消息:
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 2058, in __init__
(widgetName, self._w) + extra + self._options(cnf))
TypeError: __str__ returned non-string (type instance)
If you know how to fix this code or another way to render the image on the canvas from a BytesIO object, it will be great. 如果您知道如何修复此代码或通过BytesIO对象在画布上呈现图像的另一种方法,那将是非常不错的。 thanks
谢谢
As the error message says, pilImage is a class instance, of the ImageModule class in this case, and PhotoImage expects a string containing the file name to be opened. 如错误消息所述,在这种情况下,pilImage是ImageModule类的类实例,并且PhotoImage期望包含文件名的字符串被打开。
pilImage = ImageModule.open(bdata) ## returns instance of class
You should be able to use "test.png" as is 您应该可以按原样使用“ test.png”
img=PhotoImage(file="/path/to/image/test.png")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.