TypeError: __str__ returned non-string (instance type)

I keep getting this strange error which I cannot solve by looking at any other entry. I am applying a background image to a tkinter canvas.

import Tkinter as tk     ## Python 2.X
import Image

root = tk.Tk(); 
background = "background.png"

photo = tk.PhotoImage(Image.open(background))
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()
canvas.create_image(0, 0, anchor="nw", image=photo)

root.mainloop()

      

But because of the last line, I am getting this error:

Traceback (most recent call last):
  File "main.py", line 40, in <module>
    canvas.create_image(0, 0, anchor="nw", image=photo)
  File "c:\Python27\lib\lib-tk\Tkinter.py", line 2279, in create_image
    return self._create('image', args, kw)
  File "c:\Python27\lib\lib-tk\Tkinter.py", line 2270, in _create
    *(args + self._options(cnf, kw))))
TypeError: __str__ returned non-string (type instance)

      

+3


source to share


2 answers


Looks like I answered my own question. First of all, I wrote syntactically incorrect statements:

background = "background.png"
photo = tk.PhotoImage(Image.open(background))

      

It should be written correctly:

background = "background.png"
photo = tk.PhotoImage(background)

      



Secondly, Tkinter does not support .png files. The correct class is ImageTk from the PIL module.

from PIL import ImageTk as itk
background = "background.png"
photo = itk.PhotoImage(file = background)

      

And notice the difference in syntax:

photo = tk.PhotoImage(background)
photo = itk.PhotoImage(file = background)

      

+3


source


In addition to the_prole's post

Relative PIL Link

Warning

A bug has been encountered in the current version of the Python Image Library that may cause images to display incorrectly. When you create an object of the PhotoImage class, the reference counts for that object don't get properly incremented, so if you don't store a reference to this object elsewhere, the PhotoImage object can be garbage collected, leaving the graphic image in the application.

For example, if you have a canvas or shortcut widget that references such an image object, save a list named .imageList in that object and add all PhotoImage objects to it as they are created. If your widget can go through a large number of images, you will also need to remove objects from this list when they are no longer in use.



Your code will look like below

import Tkinter as tk
from PIL import ImageTk as itk

root = tk.Tk(); 
background = 'background.png'

photo = itk.PhotoImage(file= background)
canvas = tk.Canvas(root, width=500, height=500)
canvas.imageList = []
canvas.pack()
canvas.create_image(0, 0, anchor="nw", image=photo)
canvas.imageList.append(photo)

root.mainloop()

      

Also, about transparent PNG:
For example, in Photoshop, when you save an image as PNG, the PNG options can also cause the images to display incorrectly.

0


source







All Articles