Tkinter程序中tree.jpg图片无法显示问题排查求助
Tkinter图片不显示问题排查与修复
核心问题:PhotoImage对象被垃圾回收
你在问答界面创建Label时,直接把ImageTk.PhotoImage()的临时对象传给image参数,没有将这个对象保存为实例属性。Python的垃圾回收机制会自动清理无引用的临时对象,导致Label找不到图片资源,自然无法显示。
修复步骤
保存PhotoImage引用
在question类的__init__方法中,把创建的PhotoImage对象赋值给self的属性,让它持续被引用:# 原错误代码 # test = Label(self, image=ImageTk.PhotoImage((PIL.Image.open(r"tree.jpg").resize((50,50))))) # 修改后 self.img = ImageTk.PhotoImage(PIL.Image.open("tree.jpg").resize((50,50))) test = Label(self, image=self.img)优化窗口创建方式(可选但推荐)
原代码登录成功后销毁主窗口再新建Tk()实例,不符合Tkinter设计规范,容易引发异常。建议改用Toplevel创建子窗口:# 修改login方法 def login(self): if self.pwrd.get()=="a": # 隐藏登录窗口,创建子窗口 self.master.withdraw() b = Toplevel() b.geometry(f"{width}x{height}") app_b = question(b) # 关闭子窗口时恢复登录窗口(可选) def on_close(): b.destroy() self.master.deiconify() b.protocol("WM_DELETE_WINDOW", on_close) else: messagebox.showinfo("ERROR ","retry wrong password")
完整修复后的代码
from PIL import ImageTk import PIL.Image from tkinter import* from tkinter import messagebox class login_interface(Frame): def __init__(self,master=None): Frame.__init__(self,master) self.master=master self.security() def security(self): self.master.title("LOGIN") self.pack(fill=BOTH, expand=1) lbl = Label(self, text="PASSWORD").grid(column=0, row=0) self.pwrd = Entry(self,show="*") self.pwrd.focus_set() self.pwrd.grid(column=1, row=0) login = Button(self, text="login", width=20,command=self.login) login.grid(column=1, row=2) def login(self): if self.pwrd.get()=="a": self.master.withdraw() b = Toplevel() b.geometry(f"{width}x{height}") app_b=question(b) # 关闭问答窗口时恢复登录窗口 def on_close(): b.destroy() self.master.deiconify() b.protocol("WM_DELETE_WINDOW", on_close) else: messagebox.showinfo("ERROR ","retry wrong password") class question(Frame): def __init__(self,master=None): Frame.__init__(self,master) self.master=master self.master.title("Question") self.pack(fill=BOTH, expand=1) # 保存PhotoImage引用到实例属性 self.img = ImageTk.PhotoImage(PIL.Image.open("tree.jpg").resize((50,50))) test = Label(self, image=self.img) test.pack() lbl = Label(self, text="Who made the pythagoras theorem?").place(relx=0.5, rely=0.3, anchor='center') self.my_guess = Entry(self) self.my_guess.place(relx=0.5, rely=0.5, anchor='center') my_enter = Button(self, text="Enter", command=self.check).place(relx=0.5, rely=0.7, anchor='center') def check(self): if self.my_guess.get() == "Pythagoras": messagebox.showinfo("Correct","Go to Next Quiz.") else: messagebox.showinfo("Wrong", "Try Again.") a=Tk() width= a.winfo_screenwidth() height= a.winfo_screenheight() a.geometry(f"{width}x{height}") app=login_interface(a) app.mainloop()
内容的提问来源于stack exchange,提问作者ADS
相关产品推荐
相关产品推荐

