Adding a background image in python(在python中添加背景图像)
问题描述
我正在尝试将背景图像添加到 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()
这篇关于在python中添加背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在python中添加背景图像


基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01