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)
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With