问题描述
我正在使用以下代码创建一个 Tkinter 窗口并切换它显示的帧。
import tkinter
class GUI(tkinter.Tk):
def __init__(self):
tkinter.Tk.__init__(self)
self._frame = None
self.switch(Frame1)
def switch(self,frame_class):
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class Frame1(tkinter.Frame):
def __init__(self,parent):
tkinter.Frame.__init__(self,parent)
tkinter.Label(self,text="Frame1").pack()
parent.switch(Frame2) # not working
tkinter.Button(self,text="switch",command=lambda: parent.switch(Frame2)).pack() # working
class Frame2(tkinter.Frame):
def __init__(self,text="Frame2").pack()
if __name__ == '__main__':
gui = GUI()
gui.mainloop()
请注意,开关功能是在没有按钮的情况下执行的,但只能在点击时起作用。
解决方法
这是正在发生的事情:
- GUI 开始切换到第 1 帧
- 帧 1 已创建并切换到帧 2
- GUI 完成切换到第 1 帧
因此,应用程序在第 1 帧结束