本文参考:Why do my Tkinter images not?appear? (archive.org)
尽管上面引用的文章已经老到被归档了,但它提供的解决方法依然有效
——2021.8.8 python 3.7.9
无论使用tkinter.PhotoImage还是其他方法,当你向tkinter组件(widgets)添加图片时,你一定要向图片添加一个自定义的引用;否则,图片会无法显示。可以像下面这样这样将组件的属性引用到图片上,其中label.image = photo是关键:
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 8 21:26:27 2021
@author: Vector341
"""
import tkinter
root = tkinter.Tk()
class TestFrame(tkinter.Frame):
def __init__(self,master=None,**kw):
tkinter.Frame.__init__(self,master,**kw)
self.master = master
self.showImg()
def showImg(self):
photo = tkinter.PhotoImage(file="你的图片路径.png")
label = tkinter.Label(self.master,image=photo)
label.image = photo # 添加对图片的引用
label.pack()
app = TestFrame(root)
app.mainloop()
无须mainloop,图片即可显示
下面是问题发生的原因:来自Why do my Tkinter images not?appear? (archive.org)
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…
简单地说,Tkinter/Tk 库没能正确地处理对图片对象的引用,导致Python的垃圾回收机制错误地“回收”了图片对象,导致图片区域显示为空白。
|