图像只在一个按钮上工作,而不是在另一个按钮上

2024-09-29 21:40:25 发布

您现在位置:Python中文网/ 问答频道 /正文

当我用这段代码在一个框架内的按钮内执行一个图像时,它工作得很好:

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)

Tags: 代码图像image框架placebuttongif按钮
1条回答
网友
1楼 · 发布于 2024-09-29 21:40:25

简而言之,您的图像已被垃圾收集,不再显示。你必须留一份参考资料。你知道吗

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

对于需要显示的每个图像,都必须这样做

相关问题 更多 >

    热门问题