What's the difference between Tkinter's Tk and Toplevel classes?


Tkinter windows are created by initializing the Tk object first. It is the minimal part of any Tkinter application, which helps to instantiate the application. Tk helps to construct the basic building blocks of the application, such as an application window where all the widgets are placed.

However, Toplevel classes help to communicate through the internal widgets of the main application. One of the examples of toplevel classes is the Toplevel window that displays a child window other than the main window of the application. The Toplevel window works the same as the Tk, as it also can contain widgets and functionalities.


#Import the required libraries
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry

#Set the default color of the window
win.config(bg= '#acc7df')

def open_win():
   #Create a Button to Open the Toplevel Window
   top= Toplevel(win)
   top.title("Child Window")
   #Create a label in Toplevel window
   Label(top, text= "Hello World!")

   Button(win, text= "Click Me", background= "white", foreground= "red3", font= ('Helvetica 13 bold'), command= open_win).pack(pady= 50)


Running the above code will display a window that contains a button.

Now, click the "Click Me" Button to open a child window.

Published on 25-May-2021 08:49:04