問題描述
我正在嘗試將背景圖像添加到 Python 中的畫布.到目前為止,代碼如下所示:
I'm trying to add a background image to a canvas in Python. So far the code looks like this:
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:DocumentsBackground.png")
backgroundLabel=root.Label(parent,image=backgroundImage)
backgroundLabel.place(x=0,y=0,relWidth=1,relHeight=1)
self.canvas.pack()
root.mainloop()
它返回一個 AttributeError: PhotoImage
It's returning an AttributeError: PhotoImage
推薦答案
PhotoImage
不是 Tk()
實例 (root
) 的屬性.這是一個來自 Tkinter
的類.
PhotoImage
is not an attribute of the Tk()
instances (root
). It is a class from Tkinter
.
所以,你必須使用:
backgroundImage = PhotoImage("D:DocumentsBackground.gif")
注意 Label
是一個來自 Tkinter
的類...
Beware also Label
is a class from Tkinter
...
不幸的是,Tkinter.PhotoImage
僅適用于 gif 文件(和 PPM).如果您需要讀取 png 文件,您可以使用 PIL
的 ImageTk
模塊中的 PhotoImage
(是的,同名)類.
Unfortunately, Tkinter.PhotoImage
only works with gif files (and PPM).
If you need to read png files you can use the PhotoImage
(yes, same name) class in the ImageTk
module from PIL
.
這樣,這會將您的 png 圖像放入畫布中:
So that, this will put your png image in the canvas:
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()
這篇關(guān)于在python中添加背景圖像的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!