下面的代码可以工作:
img = PhotoImage(file="Image.gif")
Label(root, image=img).pack()为什么这种方式行不通呢?
Label(root, image=PhotoImage(file="Image.gif")).pack()有没有可能把所有的事情都放在一条线上?
发布于 2018-12-14 02:08:15
问题不在于语法,而在于垃圾收集。用你的缩写形式:
Label(root, image=PhotoImage(file="Image.gif")).pack()指向PhotoImage()返回的图像的指针永远不会被保存,因此图像会被垃圾回收,并且不会显示。在您的较长的形式:
img = PhotoImage(file="Image.gif")
Label(root, image=img).pack()您持有指向图像的指针,所以一切都很正常。您可以通过将工作代码包装在一个函数中并使img成为该函数的本地代码来说服自己:
from tkinter import *
root = Tk()
def dummy():
img = PhotoImage(file="Image.gif")
Label(root, image=img).pack()
dummy()
mainloop()现在,它不再显示了,因为当函数返回时,img消失了,并且您的图像被垃圾回收。现在,返回图像并将返回值保存在一个变量中:
def dummy():
img = PhotoImage(file="Image.gif")
Label(root, image=img).pack()
return img
saved_ref = dummy()你的图像又能正常工作了!解决此问题的常用方法如下:
def dummy():
img = PhotoImage(file="Image.gif")
label = Label(root, image=img)
label.image_ref = img # make a reference that persists as long as label
label.pack()
dummy()但是您可以看到,我们已经远离了一行程序!
发布于 2018-12-14 01:45:01
在第一个版本中,img保留对图像的引用。
在第二个版本中,没有对该图像的引用,pack()返回None
https://stackoverflow.com/questions/53767332
复制相似问题