无法在Tkinter中显示图像[重复]


问题内容

这个问题已经在这里有了答案

如果在函数中创建Tkinter图像,为什么不显示? (3个答案)

2年前关闭。

当我运行程序时,画布会显示出来,但图像不会显示。

canvas = Canvas(frame, width = 128, height = 128, bg= 'white')
    image_data = Image.open('NoArt.gif')
    ppm_f = ImageTk.PhotoImage(image_data)
    canvas.create_image(0, 0, image = ppm_f, anchor = NW)
    canvas.pack(side=BOTTOM)

有任何想法吗??

PS。

我有PIL ver 1.6,python 2.6和python 2.6随附的Tkinter版本


问题答案:

好的,我知道了。显然由于python处理垃圾处理的方式,图片被删除了。需要在全局范围内引用该图像。这是我最终使用的工作代码:

self.photo = PhotoImage(file="noart.ppm")
    self.Artwork = Label(self.frame, image=self.photo)
    self.Artwork.photo = self.photo
    self.Artwork.pack()

self.Artwork.photo = self.photo是重要的部分。它确保将显示图像。