Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter button not showing image

Hi i am trying to put an image as the background on one of my buttons, i have already done this on lots of other buttons in my main window but this particular button sits inside a top level window and the image doesn't load like it should, does anyone know why? (i have also tried defining the width and height of the button but that still doesn't show the image)

def rec_window():
    recw = Toplevel(width=500,height=500)
    recw.title('Record To.....')
    img1 = PhotoImage(file="C:/Users/Josh Bailey/Desktop/pi_dmx/Gif/mainmenu.gif")
    Button(recw, image=img1, command=rec_preset_1).grid(row=1, column=1)
    Button(recw, text="Preset 2", bg = 'grey70',width=40, height=12,command=rec_preset_2).grid(row=1, column=2)
    Button(recw, text="Preset 3", bg = 'grey70',width=40, height=12,command=rec_preset_3).grid(row=2, column=1)
    Button(recw, text="Preset 4", bg = 'grey70',width=40, height=12,command=rec_preset_4).grid(row=2, column=2)
    Button(recw, text="Cancel", bg='grey70', width=20, height=6, command=recw.destroy). grid(row=3,column=1,columnspan=2, pady=30)
like image 817
user2996828 Avatar asked Mar 05 '14 14:03

user2996828


People also ask

What is PIL Tkinter?

Tkinter relies on the Python Pillow (aka PIL) package for image processing capabilities. Using Pillow, a Tkinter function that displays a text-based message can instead display an image-based message. Note that depending on the purpose of an image in a Tkinter application, different coding may be required.

What is button in Tkinter?

The Button widget is used to add buttons in a Python application. These buttons can display text or images that convey the purpose of the buttons. You can attach a function or a method to a button which is called automatically when you click the button.


1 Answers

Depending on how the rest of your program is structured, your image might be getting cleared by garbage-collection:

From http://effbot.org/tkinterbook/photoimage.htm

Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

In your case, you can start your function by declaring img1 as a global variable to retain a reference:

global img1

or, if you already have img1 elsewhere in your program:

img1 = PhotoImage(file="C:/Users/Josh Bailey/Desktop/pi_dmx/Gif/mainmenu.gif")
img1Btn = Button(recw, image=img1, command=rec_preset_1)
img1Btn.image = img1
img1Btn.grid(row=1, column=1)
like image 152
atlasologist Avatar answered Sep 28 '22 12:09

atlasologist