无法在tkinter Label组件中显示图片的技术求助
解决Tkinter Label组件图片无法显示的问题
问题根源
你遇到的问题是ImageTk.PhotoImage创建的图片对象如果是局部变量,在__init__方法执行完毕后会被Python的垃圾回收机制清理,导致Label组件无法找到对应的图片资源,最终显示空白。
修复后的代码
只需要将图片对象绑定为类的实例属性,避免被垃圾回收:
import tkinter as tk from PIL import Image, ImageTk class LoginPage(tk.Tk): def __init__(self, WindowName='Login', WindowWidth=960, WindowHeight=540, bgColor='#181A20'): super().__init__() self.title(WindowName) self.configure(background=bgColor) # 窗口居中 scr_width = self.winfo_screenwidth() scr_height = self.winfo_screenheight() x = (scr_width/2) - (WindowWidth/2) y = (scr_height/2)-(WindowHeight/2) self.geometry('%dx%d+%d+%d' % (WindowWidth, WindowHeight, x, y)) # 设置窗口图标 png = Image.open('./res/logo_no_text_yellow.png') png = png.resize((50, 50)) self.photo = ImageTk.PhotoImage(png) self.wm_iconphoto(False, self.photo) # 主Logo标签 self.label = tk.Label(self, background=bgColor) png1 = Image.open('./res/logo yellow.png') png1 = png1.resize((148, 148)) self.photo1 = ImageTk.PhotoImage(png1) # 绑定为实例属性 self.label.configure(image=self.photo1) self.label.place(x=285, y=24) test = LoginPage() test.mainloop()
核心修改说明
- 将
photo1改为self.photo1,把图片对象绑定到类实例上,让Python不会轻易回收该资源 - 同时给窗口图标的
photo也加上self.photo绑定,避免窗口图标后续出现消失问题
内容的提问来源于stack exchange,提问作者CFYusaCapraz
相关产品推荐
相关产品推荐

