How to switch between two frames in Tkinter?


In most cases, you need to have several screens to allow the user to switch between different segments of your program. One way to achieve this is to create separate frames that lie inside the main window.

A-Frame widget is used to group too many widgets in the application. We can add separate widgets in two different frames. The user can switch to the frame from one to another by clicking the button.


In this application, we will create two separate frames greet frame and order frame. Each frame consists of two different objects. A Button will be used to switch between two different frame objects.

# Import the required libraries
from tkinter import *
from tkinter import font

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window

# Create two frames in the window
greet = Frame(win)
order = Frame(win)

# Define a function for switching the frames
def change_to_greet():
   greet.pack(fill='both', expand=1)

def change_to_order():
   order.pack(fill='both', expand=1)

# Create fonts for making difference in the frame
font1 = font.Font(family='Georgia', size='22', weight='bold')
font2 = font.Font(family='Aerial', size='12')

# Add a heading logo in the frames
label1 = Label(greet, text="Hey There! Welcome to TutorialsPoint.", foreground="green3", font=font1)

label2 = Label(order, text="Find all the interesting Tutorials.", foreground="blue", font=font2)

# Add a button to switch between two frames
btn1 = Button(win, text="Switch to Greet", font=font2, command=change_to_order)

btn2 = Button(win, text="Switch to Order", font=font2, command=change_to_greet)



Running the above code will display a window that contains two different frames.

The frames can be switched from one to another using a Button defined in it.

Published on 18-Jun-2021 13:25:24