Tkinter调用destroy()方法报错及图片不显示问题求助
Tkinter多帧切换问题修复:NameError与图片不显示
问题1:NameError: 'frame'未定义
- 原因:
frame是firstWindow方法内的局部变量,startGame方法无法跨方法访问局部变量。 - 修复:把
frame定义为类的实例属性,在firstWindow里用self.frame代替frame,startGame里用self.frame.destroy()来销毁当前帧。
问题2:界面图片无法显示
- 原因:
PhotoImage对象是局部变量,firstWindow方法执行完后,Python会回收这个没有被外部引用的对象,Label自然加载不到图片。 - 修复:将
picture定义为类的实例属性self.picture,保持对图片对象的引用。
额外修复:loadGame方法参数缺失
loadGame作为类的方法,必须包含self参数,否则点击Load Game按钮时会触发参数不匹配的错误。另外原Cancel按钮的command=window.mainloop会导致程序无法正常退出,改为window.destroy更合理。
完整修正代码
from tkinter import * import sys, os class Interface: def startGame(self): self.frame.destroy() # 使用实例属性访问frame frame2 = Frame(window, background="black") frame2.place(x=100,y=220) entry = Entry(frame2, bg="black", fg="white", font=("Comic Sans", 30,"underline")) entry.pack() login = Button(frame2, text="Login") login.pack() cancel = Button(frame2, text="Cancel", command=window.destroy) cancel.pack() def loadGame(self): # 添加self参数 pass def firstWindow(self): self.frame = Frame(window) # 定义为实例属性 self.picture = PhotoImage(file="dinossaur.png") # 定义为实例属性 label = Label(self.frame, text="Final Project: Ultimate", font=("Comic Sans", 40, "italic"), fg="gray", background="maroon", image=self.picture, compound="bottom") self.frame.pack() start = Button(self.frame, text="Start Game", command=self.startGame) load = Button(self.frame, text="Load Game", command=self.loadGame) exitB = Button(self.frame, text="Exit", command=window.destroy) label.pack() start.place(x=220,y=240) load.place(x=220,y=270) exitB.place(x=220,y=300) window = Tk() window.geometry("640x480") window.title("Final Project: Ultimate") window.config(background="maroon") game = Interface() game.firstWindow() window.mainloop()
内容的提问来源于stack exchange,提问作者Joao Roberto Santos
相关产品推荐
相关产品推荐

