Search code examples
pythonpython-3.xtkintertkinter-button

Switch frames in Tkinter without a button


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.


Solution

  • This is what is happening:

    1. GUI starts to switch to frame 1
    2. Frame1 is created and switches to frame 2
    3. GUI finishes switch to frame 1

    The app, therefore, ends up on frame 1