Python 3 – Tkinter Toplevel
Introduction
Tkinter is a widely-used library for implementing Graphical User Interfaces (GUI) in Python. Tkinter is based on the Tk graphical toolkit which was developed for the Tcl scripting language. The Toplevel widget in Tkinter is used to create separate windows in a GUI. It is similar to the main window but is independent of it. In this article, we will explore the Toplevel widget in Tkinter in detail.
Creating a Toplevel Widget
Creating a Toplevel widget is a simple task. We first create the main window and then create the Toplevel widget in it. Here is the code to create a Toplevel widget:
import tkinter as tk
root = tk.Tk()
top = tk.Toplevel(root)
root.mainloop()
Here, we have imported the tkinter
library and created a Tk
object which represents the main window. Then, we have created a Toplevel
object top
in the main window using the Toplevel
method. We have then called the mainloop
method on the Tk
object to start the event loop.
Adding Widgets to a Toplevel Widget
Once we have created a Toplevel widget, we can add widgets to it just like we would to the main window. Here is an example code that creates a Toplevel widget and adds a label and a button to it:
import tkinter as tk
root = tk.Tk()
top = tk.Toplevel(root)
lbl = tk.Label(top, text="Hello World")
lbl.pack()
btn = tk.Button(top, text="Click Me")
btn.pack()
root.mainloop()
Here, we have created a Toplevel
object top
in the main window using the Toplevel
method. We have then created a Label
object lbl
and a Button
object btn
inside the top
object. We have then called the pack
method on these objects to add them to the Toplevel widget.
Destroying a Toplevel Widget
When we create a Toplevel widget, it is a separate window that is independent of the main window. We can destroy this window using the destroy
method. Here is an example code that creates a Toplevel widget with a button that destroys it:
import tkinter as tk
root = tk.Tk()
def create_window():
top = tk.Toplevel(root)
lbl = tk.Label(top, text="Hello World")
lbl.pack()
btn_close = tk.Button(top, text="Close", command=top.destroy)
btn_close.pack()
btn_create = tk.Button(root, text="Create Window", command=create_window)
btn_create.pack()
root.mainloop()
Here, we have created a main window with a button btn_create
that creates a Toplevel window when clicked using the create_window
function. Inside the create_window
function, we have created a Toplevel widget and added a label and a button to it. The button btn_close
inside the Toplevel widget has the command
parameter set to top.destroy
which calls the destroy
method on the Toplevel widget when clicked.
Conclusion
The Toplevel widget in Tkinter is an important tool for creating separate windows in a GUI application. We have learned how to create a Toplevel window, add widgets to it, and destroy it in this article. This knowledge can be applied to create complex GUIs in Python using the Tkinter library.