Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What's the difference between Tkinter's Tk and Toplevel classes?
Tkinter provides two main window classes: Tk and Toplevel. Understanding their differences is crucial for building multi-window applications.
Tk Class
The Tk class creates the main application window and serves as the root of your GUI application. Every Tkinter application must have exactly one Tk instance, which initializes the GUI toolkit and provides the foundation for all other widgets.
Key Features of Tk
- Creates the main application window
- Only one Tk instance per application
- Contains the main event loop (
mainloop()) - Closing it terminates the entire application
Toplevel Class
The Toplevel class creates additional windows that are separate from the main window but still part of the same application. These are often called child windows or dialog windows.
Key Features of Toplevel
- Creates secondary windows
- Can have multiple Toplevel instances
- Depends on the main Tk window
- Closing it doesn't terminate the application
Example
Here's a practical example showing both classes in action ?
# Import the required libraries
from tkinter import *
# Create an instance of Tkinter Frame (Main Window)
win = Tk()
# Set the geometry
win.geometry("700x350")
win.title("Main Window")
# Set the default color of the window
win.config(bg='#acc7df')
def open_win():
# Create a Toplevel Window (Child Window)
top = Toplevel(win)
top.geometry("500x250")
top.title("Child Window")
top.config(bg='#f0f0f0')
# Create a label in Toplevel window
Label(top, text="Hello World!", font=('Arial', 16), bg='#f0f0f0').pack(pady=50)
# Add a close button in the child window
Button(top, text="Close", command=top.destroy).pack()
# Create a button in main window to open the child window
Button(win, text="Open Child Window", background="white", foreground="red3",
font=('Helvetica', 13, 'bold'), command=open_win).pack(pady=50)
win.mainloop()
Comparison
| Feature | Tk Class | Toplevel Class |
|---|---|---|
| Purpose | Main application window | Secondary/child windows |
| Instances | Only one per application | Multiple allowed |
| Event Loop | Contains mainloop() | Uses parent's event loop |
| Closing Effect | Terminates entire application | Closes only that window |
Common Use Cases
Use Tk for:
- Main application interface
- Primary user interaction window
Use Toplevel for:
- Settings/preferences dialogs
- About windows
- Error messages or alerts
- Additional tool windows
Conclusion
Use Tk for your main application window and Toplevel for secondary windows. Remember that every application needs exactly one Tk instance, while you can create multiple Toplevel windows as needed.
