我一直得到这个奇怪的错误,我无法解决任何其他帖子。我将背景图片应用于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()
但由于最后一行,我收到了这个错误:
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)
答案 0 :(得分:5)
看起来我回答了自己的问题。首先,我编写了语法错误的语句:
background = "background.png"
photo = tk.PhotoImage(Image.open(background))
这应该写得正确:
background = "background.png"
photo = tk.PhotoImage(background)
其次,Tkinter不支持.png文件。正确的类是来自模块PIL的ImageTk。
from PIL import ImageTk as itk
background = "background.png"
photo = itk.PhotoImage(file = background)
注意语法上的差异:
photo = tk.PhotoImage(background)
photo = itk.PhotoImage(file = background)
答案 1 :(得分:0)
警告
当前版本的Python Imaging Library存在一个错误 这可能导致您的图像无法正常显示。当你创建一个 类PhotoImage的对象,该对象的引用计数 没有得到适当的增加,所以除非你保持对它的引用 在其他地方的对象,PhotoImage对象可能是垃圾收集, 将您的图形留在应用程序上。
例如,如果您有一个引用此类的画布或标签小部件 一个图像对象,在该对象中保留一个名为.imageList的列表 在创建时将所有PhotoImage对象附加到它。如果你的 小部件可能会循环通过大量图像,您也会想要 在不再使用时从这个列表中删除它们。
您的代码如下
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()
另外,关于透明的PNG:
例如,在Photoshop中,当您将图片保存为PNG时,PNG选项也会导致图像无法正常显示。