Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an image for the background in tkinter?

Tags:

python

tkinter

#import statements
from Tkinter import *
import tkMessageBox
import tkFont
from PIL import ImageTk,Image

Code to import image:

app = Tk()
app.title("Welcome")
image2 =Image.open('C:\\Users\\adminp\\Desktop\\titlepage\\front.gif')
image1 = ImageTk.PhotoImage(image2)
w = image1.width()
h = image1.height()
app.geometry('%dx%d+0+0' % (w,h))
#app.configure(background='C:\\Usfront.png')
#app.configure(background = image1)

labelText = StringVar()
labelText.set("Welcome !!!!")
#labelText.fontsize('10')

label1 = Label(app, image=image1, textvariable=labelText,
               font=("Times New Roman", 24),
               justify=CENTER, height=4, fg="blue")
label1.pack()

app.mainloop()

This code doesn't work. I want to import a background image.

like image 335
user1276381 Avatar asked Apr 15 '12 00:04

user1276381


People also ask

Can you use PNG in Tkinter?

Tkinter PhotoImage only supports the GIF, PGM, PPM, and PNG file formats. Use the PhotoImage widget from the PIL. ImageTk module to support other file formats.


1 Answers

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.

For example:

background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.

Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:

background_label.image = background_image
like image 80
Bryan Oakley Avatar answered Oct 01 '22 19:10

Bryan Oakley