Luke H
Luke H

Reputation: 117

Image working in one button but not another

When I use this code to execute an image inside a button within a frame it works just fine:

image2= PhotoImage(file="questionmark.gif")
f3buttonQ=Button(f3,image=image2, command = findcustomer).place(x=425,y=10)

However, when I just want to use this in the root frame I use this code:

image2= PhotoImage(file="questionmark.gif")
f3buttonQ=Button(root, image=image2,command = findcustomer).place(x=450,y=110)

The image doesn't load in the latter piece of code and the only difference between the two would be the f3 in the first one. Thanks.

Update:

So I managed to get the command to work by using this:

photo2= tk.PhotoImage(file="questionmark.gif")
button = Button(image=photo2,command = findcustomer).place(x=450,y=110)

When I run this alone the image is loaded just perfectly onto the button, but when I add this line under it they both go blank again and the image isn't loaded:

f3findProduct=Button(image=photo2, command = findproduct).place(x=110,y=190)

Upvotes: 0

Views: 63

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36682

The short story is that your image is garbage collected and is no longer displayed. You must keep a reference of it.

from effbot:

When you add a PhotoImage or other Image object to a Tkinter widget, you must keep your own reference to the image object. If you don’t, the image won’t always show up.

The problem is that the Tkinter/Tk interface doesn’t handle references to Image objects properly; the Tk widget will hold a reference to the internal object, but Tkinter does not. When Python’s garbage collector discards the Tkinter object, Tkinter tells Tk to release the image. But since the image is in use by a widget, Tk doesn’t destroy it. Not completely. It just blanks the image, making it completely transparent…

The solution is to make sure to keep a reference to the Tkinter object, for example by attaching it to a widget attribute:

photo = PhotoImage(...)

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

You must do that for each image you need to display

Upvotes: 1

Related Questions