2012-11-30 107 views
3

我试图在Python中将背景图像添加到画布。到目前为止,代码如下所示:在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() 

它返回一个AttributeError:光象

回答

7

PhotoImage不是Tk()实例(root)的属性。这是一个Tkinter的课程。

所以,你必须使用:

backgroundImage = PhotoImage("D:\Documents\Background.gif") 

也谨防LabelTkinter类...

编辑:

不幸的是,Tkinter.PhotoImage仅适用于GIF文件(PPM) 。 如果您需要阅读PNG文件,可以使用PILImageTk模块中的PhotoImage(是,同名)类。

这样,这将会把你的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() 

enter image description here

+0

谢谢回复! 所以...我如何将图像加载到画布上? – user1689935

+0

请参阅我编辑中的示例 – joaquin

+0

是否仍有可能在图像上绘制其他东西? – user1689935

0

只是更改为:

image = Image.open("D://Engagement2/backgrounds/500x400.png") 
    backgroundImage=ImageTk.PhotoImage(image) 

相信我,这将100%工作