图像在一个按钮中工作,但在另一个按钮中不工作

Image working in one button but not another

当我使用此代码在框架内的按钮内执行图像时,效果很好:

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

但是,当我只想在根框架中使用它时,我使用以下代码:

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

图像不会在后一段代码中加载,两者之间的唯一区别是第一段代码中的 f3。谢谢

更新:

所以我设法通过使用这个命令来工作:

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

当我 运行 仅此一项时,图像就完美地加载到按钮上,但是当我在其下方添加这一行时,它们都再次变为空白并且图像未加载:

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

简而言之,您的图像已被垃圾收集,不再显示。你必须保留它的参考。

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

您必须为每张需要显示的图像执行此操作