[Solved] Function to switch between two frames in tkinter


You shouldn’t put any logic in a lambda. Just create a normal function that has any logic you want, and call it from the button. It’s really no more complicated that that.

class SomePage(...):
    def __init__(...):
        ...
        button1 = tk.Button(self, text="Back to Home", 
                        command=lambda: self.maybe_switch_page(StartPage))
        ...

    def maybe_switch_page(self, destination_page):
        if ...:
            self.controller.show_frame(destination_page)
        else:
            ...

If you want a more general purpose solution, move the logic to show_frame, and have it call a method on the current page to verify that it is OK to switch.

For example:

    class Controller(...):
        ...
        def show_frame(self, destination):
            if self.current_page is None or self.current_page.ok_to_switch():
                # switch the page
            else:
                # don't switch the page

Then, it’s just a matter of implementing ok_to_switch in every page class.

5

solved Function to switch between two frames in tkinter