I'm using the following code to create a Tkinter window and switch the frames it displays.
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()
Note that the switch function is executed without a button, yet only works on click.
This is what is happening:
The app, therefore, ends up on frame 1