在python中添加背景图片 [英] Adding a background image in python

查看:4331
本文介绍了在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:\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: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:\Documents\Background.gif")

当心Label也是Tkinter ...

不幸的是,Tkinter.PhotoImage仅适用于gif文件(和PPM). 如果需要读取png文件,则可以使用PILImageTk模块中的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中添加背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆