TypeError:__str__返回了非字符串(类型实例)

the*_*ole 5 tkinter

我一直收到这个非常奇怪的错误,无法解决其他任何帖子。我正在将背景图像应用于tkinter画布。

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()
Run Code Online (Sandbox Code Playgroud)

但是由于最后一行,我得到了这个错误:

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)
Run Code Online (Sandbox Code Playgroud)

the*_*ole 5

好像我回答了我自己的问题。首先,我编写了语法错误的语句:

background = "background.png"
photo = tk.PhotoImage(Image.open(background))
Run Code Online (Sandbox Code Playgroud)

应该正确编写:

background = "background.png"
photo = tk.PhotoImage(background)
Run Code Online (Sandbox Code Playgroud)

其次,Tkinter不支持.png文件。正确的类是模块PIL中的ImageTk。

from PIL import ImageTk as itk
background = "background.png"
photo = itk.PhotoImage(file = background)
Run Code Online (Sandbox Code Playgroud)

并注意语法上的差异:

photo = tk.PhotoImage(background)
photo = itk.PhotoImage(file = background)
Run Code Online (Sandbox Code Playgroud)