1

I want to render an image from a BytesIO object to a canvas for this I'm using this code:

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. thanks

Tarik Mokafih
  • 1,247
  • 7
  • 19
  • 38

1 Answers1

-2

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.open(bdata)  ## returns instance of class

You should be able to use "test.png" as is

img=PhotoImage(file="/path/to/image/test.png")