use*_*935 4 python background canvas python-imaging-library
我正在尝试在Python中向画布添加背景图像.到目前为止代码看起来像这样:
from Tkinter import *
from PIL import ImageTk,Image
... other stuffs
root=Tk()
canvasWidth=600
canvasHeight=400
self.canvas=Canvas(root,width=canvasWidth,height=canvasHeight)
backgroundImage=root.PhotoImage("D:\Documents\Background.png")
backgroundLabel=root.Label(parent,image=backgroundImage)
backgroundLabel.place(x=0,y=0,relWidth=1,relHeight=1)
self.canvas.pack()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
它返回一个AttributeError:PhotoImage
PhotoImage不是Tk()instances(root)的属性.这是一个班级Tkinter.
所以,你必须使用:
backgroundImage = PhotoImage("D:\Documents\Background.gif")
Run Code Online (Sandbox Code Playgroud)
也当心Label是从类Tkinter...
编辑:
不幸的是,Tkinter.PhotoImage只适用于gif文件(和PPM).如果你需要读取PNG文件,你可以使用PhotoImage(是的,相同的名字)类中ImageTk的模块PIL.
这样,这会将你的png图像放在画布上:
from Tkinter import *
from PIL import ImageTk
canvas = Canvas(width = 200, height = 200, bg = 'blue')
canvas.pack(expand = YES, fill = BOTH)
image = ImageTk.PhotoImage(file = "C:/Python27/programas/zimages/gato.png")
canvas.create_image(10, 10, image = image, anchor = NW)
mainloop()
Run Code Online (Sandbox Code Playgroud)
