By Max Tilley

2011-09-25 14:14:04 8 Comments

I have built my first few scripts with a nice little GUI on them, as the tutorials have shown me, but none of them address what to do for a more complex program.

If you have something with a 'start menu', for your opening screen, and upon user selection you move to a different section of the program and redraw the screen appropriately, what is the elegant way of doing this?

Does one just .destroy() the 'start menu' frame and then create a new one filled with the widgets for another part? And reverse this process when they press the back button?


@Stevoisiak 2018-03-16 16:42:27

One way to switch frames in tkinter is to destroy the old frame then replace it with your new frame.

I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container object and allows you to use any generic Frame class.

# Multi-frame tkinter application v2.3
import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        self._frame = None

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
        self._frame = new_frame

class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Open page one",
                  command=lambda: master.switch_frame(PageOne)).pack()
        tk.Button(self, text="Open page two",
                  command=lambda: master.switch_frame(PageTwo)).pack()

class PageOne(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

class PageTwo(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

if __name__ == "__main__":
    app = SampleApp()

Start page Page one Page two


switch_frame() works by accepting any Class object that implements Frame. The function then creates a new frame to replace the old one.

  • Deletes old _frame if it exists, then replaces it with the new frame.
  • Other frames added with .pack(), such as menubars, will be unaffected.
  • Can be used with any class that implements tkinter.Frame.
  • Window automatically resizes to fit new content

Version History


- Pack buttons and labels as they are initialized


- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.


- Remove type-hinting for backwards compatibility with Python 3.4.


- Add type-hinting for `frame_class`.


- Remove extraneous `container` frame.
    - Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
    - Frame switching is now done with `master.switch_frame()`.


- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.


  - Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
      - Initializing the frame before calling `.destroy()` results
        in a smoother visual transition.


- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
    - Remove `new_frame` variable.


- Rename `parent` to `master` for consistency with base `Frame` class.


- Remove `main()` function.


- Rename `frame` to `_frame`.
    - Naming implies variable should be private.
- Create new frame before destroying old frame.


- Initial version.

@quantik 2018-04-03 14:27:09

I get this weird bleed-over of frames when I try this method not sure if it can be replicated:

@Stevoisiak 2018-04-04 17:56:42

@quantik The bleed-over effect happens because the old buttons aren't being destroyed properly. Make sure you are attaching buttons directly to the frame class (usually self).

@Stevoisiak 2018-05-22 17:14:42

In hindsight, the name switch_frame() could be a bit misleading. Should I rename it to replace_frame()?

@Deepworks 2018-09-24 11:40:32

How can i switch the frames by keeping the class files in different files

@Stevoisiak 2018-09-24 18:35:48

@Deepworks I hadn't considered multiple class files. Unfortunately, multiple files may be prone to circular dependencies.

@Bryan Oakley 2018-11-06 13:21:18

i recommend removing the version history part of this answer. It's completely useless. If you want to see the history, stackoverflow provides a mechanism to do that. Most people who read this answer won't care about the history.

@Vasyl Vaskivskyi 2019-02-28 23:12:55

Thank you for the version history. It is good to know that you updated and revised the answer over time.

@martineau 2019-04-27 16:57:38

I can't reproduce the "unintended side effect" when I run the code in @Bryan's answer—so don't understand that premise...

@Bryan Oakley 2011-09-26 14:55:21

One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.

Note: for this to work, all of the widgets for a page must have that page (ie: self) or a descendant as a parent (or master, depending on the terminology you prefer).

Here's a bit of a contrived example to show you the general concept:

import tkinter as tk                # python 3
from tkinter import font  as tkfont # python 3
#import Tkinter as tk     # python 2
#import tkFont as tkfont  # python 2

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")


    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))

if __name__ == "__main__":
    app = SampleApp()

start page page 1 page 2

If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.

For example, to create the classes individually you can remove the loop (for F in (StartPage, ...) with this:

self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)

self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")

Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:

@Max Tilley 2011-09-27 09:18:48

Wow, thank you so much. Just as an academic question rather than a practical one, how many of these pages hidden on top of each other would you need before it started to start becoming laggy and unresponsive?

@Bryan Oakley 2011-09-27 12:50:18

I don't know. Probably thousands. It would be easy enough to test.

@Parallax Sugar 2017-06-14 15:11:10

Is there no truly simple way of achieving an affect similar to this, with much fewer lines of code, without having to stack frames on top of each other?

@Bryan Oakley 2017-06-14 15:15:01

@LauraCookson: there are definitely simpler ways of achieving this, with or without stacking frames. In the absolute simplest case, create a frame with whatever you want. When you are ready to switch, destroy it and create something else.

@Stevoisiak 2018-03-21 17:20:01

Aran-Fey pointed out that there is a .pack_forget method you can use to hide unneeded frames without deleting them.

@Bryan Oakley 2018-03-21 17:45:18

@StevenVascellaro: yes, pack_forget can be used if you're using pack.

@Stevoisiak 2019-05-21 18:35:36

Warning: It is possible for users select "hidden" widgets on background frames by pressing Tab, then activate them with Enter.

@recobayu 2015-07-24 06:24:45

Here is another simple answer, but without using classes.

from tkinter import *

def raise_frame(frame):

root = Tk()

f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)

for frame in (f1, f2, f3, f4):
    frame.grid(row=0, column=0, sticky='news')

Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()

Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()

Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')

Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()


@velpandian 2018-03-02 03:50:42

How we can show label, button in big size. It seems frame has small width and height. Even after increasing window dimensions using root.geometry()

Related Questions

Sponsored Content

23 Answered Questions

[SOLVED] What is the difference between @staticmethod and @classmethod?

24 Answered Questions

[SOLVED] Limiting floats to two decimal points

41 Answered Questions

[SOLVED] How to merge two dictionaries in a single expression?

20 Answered Questions

22 Answered Questions

[SOLVED] Difference between __str__ and __repr__?

25 Answered Questions

[SOLVED] How do I concatenate two lists in Python?

44 Answered Questions

[SOLVED] Replacements for switch statement in Python?

25 Answered Questions

[SOLVED] Get difference between two lists

1 Answered Questions

Python tkinter show text in frame after buttonclick

  • 2018-03-04 14:52:08
  • Andre Jochemsen
  • 1175 View
  • -2 Score
  • 1 Answer
  • Tags:   python tkinter frame

2 Answered Questions

[SOLVED] Python/Tkinter quit button for stacked frames

Sponsored Content