2012-11-30 180 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%工作