The Wayback Machine - https://web.archive.org/web/20241116123515/https://www.geeksforgeeks.org/tkinter-application-to-switch-between-different-page-frames/
Open In App

Tkinter Application to Switch Between Different Page Frames

Last Updated : 11 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: Python GUI – tkinter

Sometimes it happens that we need to create an application with several pops up dialog boxes, i.e Page Frames. Here is a step by step process to create multiple Tkinter Page Frames and link them! This can be used as a boilerplate for more complex python GUI applications like creating interfaces for Virtual Laboratories for experiments, classrooms, etc.

Here are the steps: 

  • Create three different pages. Here we have three different pages, The start page as the home page, page one, and page two. 
  • Create a container for each page frame. 
  • We have four classes. First is the tkinterApp class, where we have initialized the three frames and defined a function show_frame which is called every time the user clicks on a button. 
  • The StartPage is simple with two buttons to go to Page 1 and Page 2. 
  • Page 1 has two buttons, One for Page 2 and another to return to Start Page. 
  • Page 2 also has two buttons, one for Page 1 and others to return to StartPage. 
  • This is a simplistic application of navigating between Tkinter frames. 
  • This can be used as a boilerplate for more complex applications and several features can be added. 

The App starts with the StartPage as the first page, as shown in class tkinterApp. Here in StartApp, there are two buttons. Clicking on a button takes you to the respective Page. You can add images and graphs to these pages and add complex functionality. The pages have two buttons as well. Every time a button is pressed show_frame is called, which displays the respective Page.

Below is the implementation: 

Python3




import tkinter as tk
from tkinter import ttk
  
 
LARGEFONT =("Verdana", 35)
  
class tkinterApp(tk.Tk):
     
    # __init__ function for class tkinterApp
    def __init__(self, *args, **kwargs):
         
        # __init__ function for class Tk
        tk.Tk.__init__(self, *args, **kwargs)
         
        # creating a container
        container = tk.Frame(self) 
        container.pack(side = "top", fill = "both", expand = True)
  
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)
  
        # initializing frames to an empty array
        self.frames = {} 
  
        # iterating through a tuple consisting
        # of the different page layouts
        for F in (StartPage, Page1, Page2):
  
            frame = F(container, self)
  
            # initializing frame of that object from
            # startpage, page1, page2 respectively with
            # for loop
            self.frames[F] = frame
  
            frame.grid(row = 0, column = 0, sticky ="nsew")
  
        self.show_frame(StartPage)
  
    # to display the current frame passed as
    # parameter
    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
  
# first window frame startpage
  
class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
         
        # label of frame Layout 2
        label = ttk.Label(self, text ="Startpage", font = LARGEFONT)
         
        # putting the grid in its place by using
        # grid
        label.grid(row = 0, column = 4, padx = 10, pady = 10)
  
        button1 = ttk.Button(self, text ="Page 1",
        command = lambda : controller.show_frame(Page1))
     
        # putting the button in its place by
        # using grid
        button1.grid(row = 1, column = 1, padx = 10, pady = 10)
  
        ## button to show frame 2 with text layout2
        button2 = ttk.Button(self, text ="Page 2",
        command = lambda : controller.show_frame(Page2))
     
        # putting the button in its place by
        # using grid
        button2.grid(row = 2, column = 1, padx = 10, pady = 10)
  
          
  
  
# second window frame page1
class Page1(tk.Frame):
     
    def __init__(self, parent, controller):
         
        tk.Frame.__init__(self, parent)
        label = ttk.Label(self, text ="Page 1", font = LARGEFONT)
        label.grid(row = 0, column = 4, padx = 10, pady = 10)
  
        # button to show frame 2 with text
        # layout2
        button1 = ttk.Button(self, text ="StartPage",
                            command = lambda : controller.show_frame(StartPage))
     
        # putting the button in its place
        # by using grid
        button1.grid(row = 1, column = 1, padx = 10, pady = 10)
  
        # button to show frame 2 with text
        # layout2
        button2 = ttk.Button(self, text ="Page 2",
                            command = lambda : controller.show_frame(Page2))
     
        # putting the button in its place by
        # using grid
        button2.grid(row = 2, column = 1, padx = 10, pady = 10)
  
  
  
  
# third window frame page2
class Page2(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = ttk.Label(self, text ="Page 2", font = LARGEFONT)
        label.grid(row = 0, column = 4, padx = 10, pady = 10)
  
        # button to show frame 2 with text
        # layout2
        button1 = ttk.Button(self, text ="Page 1",
                            command = lambda : controller.show_frame(Page1))
     
        # putting the button in its place by
        # using grid
        button1.grid(row = 1, column = 1, padx = 10, pady = 10)
  
        # button to show frame 3 with text
        # layout3
        button2 = ttk.Button(self, text ="Startpage",
                            command = lambda : controller.show_frame(StartPage))
     
        # putting the button in its place by
        # using grid
        button2.grid(row = 2, column = 1, padx = 10, pady = 10)
  
  
# Driver Code
app = tkinterApp()
app.mainloop()


Output:

switch-between-different-page-frames-python-1switch-between-different-page-frames-python-2

 Code Explanation:

  1. The code starts by creating a class, tkinterApp.
  2. This class has two main functions: _init_ and show_frame.
  3. The _init_ function is used to initialize the objects in the application.
  4. The first function, _init_ for the class Tk, is used to initialize the object tkinterApp.
  5. It takes two arguments: *args and **kwargs.
  6. The first argument is an empty list of strings, while the second argument is a dictionary of key-value pairs that are passed to various methods in Tkinter.
  7. Next, the code creates a container object called container and packs it into a frame onscreen with side set to “top” and fill set to “both”.
  8. The expand property of container is set to True so that it will automatically be expanded when displayed onscreen.
  9. Finally, grid_rowconfigure() and grid_columnconfigure() are used to configure the rows and columns of container respectively.
  10. Now that everything is setup, the code starts iterating through different page layouts using for loop.
  11. For each layout (StartPage, Page1, Page2), a new frame instance (F) is created and initialized with values from startpage (the first layout), page
  12. The code creates a Tkinter application and defines three frames, StartPage, Page1, and Page2.
  13. The _init_ function for the class tkinterApp is used to initialize the frames and container.
  14. The container is then packed into a Frame object and displayed on-screen.
  15. The code first iterates through a tuple consisting of the different page layouts.
  16. For each layout, a Frame object is created and initialized with the appropriate parameters.
  17. The Frame objects are then placed in respective containers and displayed on-screen.
  18. When the user clicks on one of the buttons, the show_frame function is called which invokes the controller’s show_frame function for that particular page layout.


Previous Article
Next Article

Similar Reads

Scrollable Frames in Tkinter
A scrollbar is a widget that is useful to scroll the text in another widget. For example, the text in Text, Canvas Frame or Listbox can be scrolled from top to bottom or left to right using scrollbars. There are two types of scrollbars. They are horizontal and vertical. The horizontal scrollbar is useful to view the text from left to right. The ver
3 min read
Create Multiple frames with Grid manager using Tkinter
Prerequisites: Tkinter Tkinter can support the creation of more than one widget in the same frame. Not just this it also supports a mechanism to align them relative to each other. One of the easiest ways of aligning the different widgets in the Tkinter is through grid manager. Apart from aligning various widgets, the grid manager can also be used f
2 min read
How to Display Images within Tkinter Frames
Tkinter is a Python module used to create Graphical User Interface (GUI) applications. Tkinter has many widgets such as Button, Label, Text, Entry, Frame, Checkbox and more that make it easy and quick to develop desktop applications. How to Insert Image inside Frame in Tkinter?To insert an image inside a frame is the same as inserting an image in T
1 min read
Difference Between The Widgets Of Tkinter And Tkinter.Ttk In Python
Python offers a variety of GUI (Graphical User Interface) frameworks to develop desktop applications. Among these, Tkinter is the standard Python interface to the Tk GUI toolkit. Tkinter also includes the 'ttk' module, which enhances the visual appeal and functionality of the applications. In this article, we will cover the differences, providing a
4 min read
On/Off Toggle Button Switch in Tkinter
Prerequisite: Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we wi
2 min read
Find Columns Shared By Two Data Frames
Pandas is the open-source Python library used for Data analysis and manipulation. It is fast, powerful, flexible, and easy to use. In this article, we will discuss how to find columns that are common between two Data Frames. Below is the different approach that can be used to find common columns. Method 1: Using Numpy intersect1d method In this exa
2 min read
MoviePy – Iterating frames of Video File Clip
In this article we will see how we can iterate frames of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. A video is basically combination of lots of frame for each time there is a specific frame, in order to get the frame at given time we use get_frame method.
2 min read
How to handle Frames/iFrames in Selenium with Python
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. HTML outlines are utilized to isolate your program window into numerous segments where eac
2 min read
Extract Video Frames from Webcam and Save to Images using Python
There are two libraries you can use: OpenCV and ImageIO. Which one to choose is situation-dependent and it is usually best to use the one you are already more familiar with. If you are new to both then ImageIO is easier to learn, so it could be a good starting point. Whichever one you choose, you can find examples for both below: ImageIOInstallatio
2 min read
Save frames of live video with timestamps - Python OpenCV
Images are very important data nowadays from which we can obtain a lot of information which will helpful for analysis. Sometimes data to be processed can be in the form of video. To process this kind of data we have to read video extract frames and save them as images. Security camera videos we have seen that there is a timestamp and date at top of
3 min read
Create MySQL Database Login Page in Python using Tkinter
Prerequisites: Python GUI – tkinter, Python MySQL – Select QueryTkinter is one of the Python libraries which contains many functions for the development of graphic user interface pages and windows. Login pages are important for the development of any kind of mobile or web application. This page is most essential for user authentication purposes.We
2 min read
Python | ToDo GUI Application using Tkinter
Prerequisites : Introduction to tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create a ToDo GUI application using Tkinter, with a step-by-step guide. To create a tkinter : Importing the module – tkinter
5 min read
GUI chat application using Tkinter in Python
Chatbots are computer program that allows user to interact using input methods. The Application of chatbots is to interact with customers in big enterprises or companies and resolve their queries. Chatbots are mainly built for answering standard FAQs. The benefit of this type of system is that customer is no longer required to follow the same tradi
7 min read
Build GUI Application for Guess Indian State using Tkinter Python
In this article, you will learn to make a GUI game in Python, in which we will be shown a map of Indian states and an input prompt were in the prompt, the user has to enter a state name of India. If the user guessed it correctly, the name would hover over its location on the map. You can also see the score as the title of the input prompt window. M
8 min read
Create First GUI Application using Python-Tkinter
We are now stepping into making applications with graphical elements, we will learn how to make cool apps and focus more on its GUI(Graphical User Interface) using Tkinter. What is Tkinter?Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python sta
12 min read
Different messages in Tkinter | Python
Tkinter provides a messagebox class which can be used to show variety of messages so that user can respond according to those messages. Messages like confirmation message, error message, warning message etc.In order to use this class one must import this class as shown below: # import all the functions and constants of this class. from tkinter.mess
2 min read
Python Tkinter | Create different type of lines using Canvas class
In Tkinter, Canvas.create_line() method is used to create lines in any canvas. These lines can only be seen on canvas so first, you need to create a Canvas object and later pack it into the main window. Syntax: Canvas.create_line(x1, y1, x2, y2, ...., options = ...) Note: Minimum of 4 points are required to create a line, but you can also add multi
2 min read
Python Tkinter | Create different shapes using Canvas class
In Tkinter, Canvas class is used to create different shapes with the help of some functions which are defined under Canvas class. Any shape that Canvas class creates requires a canvas, so before creating any shapes a Canvas object is required and needs to be packed to the main window. Canvas Methods for shapes: Canvas.create_oval(x1, y1, x2, y2, op
3 min read
An application to test the given page is found or not on the server using Python
Prerequisite: Python Urllib module In this article, we are going to write scripts to test whether the given page is found on the server or not with a GUI application. We need to Install Urllib Module to carry out this operation. Type this command in your terminal. pip install urllib Approach: Import urllib module.Read URL with urllib.request.urlope
2 min read
Build an Application to Search Installed Application using Python
In this article, we are going to write python scripts to search for an installed application on Windows and bind it with the GUI application. We are using winapps modules for managing installed applications on Windows. Prerequisite - Tkinter in Python To install the module, run this command in your terminal: pip install winapps Below is what the GU
6 min read
Difference Between "Fill" and "Expand" Options for Tkinter Pack Method
Efficient layout management is crucial in creating visually appealing and user-friendly graphical user interfaces (GUIs). In the world of Python GUI programming, Tkinter stands out as a popular choice due to its simplicity and versatility. One of the key techniques used in Tkinter for layout management is the Pack method. In this article, we'll del
4 min read
How to Switch between Window using Selenium in Python?
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. It's miles fantastically viable that we open a massive range of windows. Each window might
2 min read
PyQt5 – Different padding size at different edge of Label
In this article, we will see how we can add different padding size at different edges. Below is a image of label with normal padding and a label with different padding size at different edge. In order to do this we will use setStyleSheet() method and describe padding length for each edge. Syntax : label.setStyleSheet("border :3px solid black;" "pad
2 min read
PyQt5 - Setting different toolTip to different item of ComboBox
In this article we will see how we can set different tooltip to the different items of the combo box. We can set tooltip to the combo box with the help of setToolTip method and for setting tooltip to the view part we have to use view object with this method. Below is the representation of how individual item tool tip look like. In order to do we ha
2 min read
How to apply different titles for each different subplots using Plotly in Python?
Prerequisites: Python Plotly In this article, we will explore how to apply different titles for each different subplot. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears. It provides us
2 min read
Python | askopenfile() function in Tkinter
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to
2 min read
Python | Binding function in Tkinter
Tkinter is a GUI (Graphical User Interface) module that is widely used in desktop applications. It comes along with the Python, but you can also install it externally with the help of pip command. It provides a variety of Widget classes and functions with the help of which one can make our GUI more attractive and user-friendly in terms of both look
3 min read
Make Notepad using Tkinter
Let's see how to create a simple notepad in Python using Tkinter. This notepad GUI will consist of various menu like file and edit, using which all functionalities like saving the file, opening a file, editing, cut and paste can be done. Now for creating this notepad, Python 3 and Tkinter should already be installed in your system. You can download
6 min read
Facts App Using Tkinter module
This is an app that will provide us with Facts. With Python, we can make things very easy. We have a very amazing library so that we can do it. We just need two of the libraries and if we just combine the concept, we will be able to make a new thing. We just have to use tkinter and randfacts to do this so. Module RequiredTkinter: The tkinter packag
2 min read
Color game using Tkinter in Python
TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games. Let's try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to play this game is 30 seconds. Colors used in this
4 min read
Practice Tags :
three90RightbarBannerImg