Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a background image in 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()

It's returning an AttributeError: PhotoImage

like image 418
user1689935 Avatar asked Nov 30 '12 00:11

user1689935


1 Answers

PhotoImage is not an attribute of the Tk() instances (root). It is a class from Tkinter.

So, you must use:

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

Beware also Label is a class from Tkinter...

Edit:

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.

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()

enter image description here

like image 152
joaquin Avatar answered Sep 28 '22 00:09

joaquin