无需按钮即可在 Tkinter 中切换帧
Switch frames in Tkinter without a button
我正在使用以下代码创建 Tkinter window 并切换它显示的框架。
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, parent):
tkinter.Frame.__init__(self, parent)
tkinter.Label(self, text="Frame2").pack()
if __name__ == '__main__':
gui = GUI()
gui.mainloop()
请注意,切换功能是在没有按钮的情况下执行的,但仅在单击时起作用。
这是正在发生的事情:
- GUI 启动 切换到第 1 帧
- 第 1 帧已创建并切换到第 2 帧
- GUI 完成 切换到第 1 帧
因此,该应用在第 1 帧结束
我正在使用以下代码创建 Tkinter window 并切换它显示的框架。
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, parent):
tkinter.Frame.__init__(self, parent)
tkinter.Label(self, text="Frame2").pack()
if __name__ == '__main__':
gui = GUI()
gui.mainloop()
请注意,切换功能是在没有按钮的情况下执行的,但仅在单击时起作用。
这是正在发生的事情:
- GUI 启动 切换到第 1 帧
- 第 1 帧已创建并切换到第 2 帧
- GUI 完成 切换到第 1 帧
因此,该应用在第 1 帧结束