Python - GUI Programming - Toplevel Widget

The Toplevel widget is used to create separate windows, pop-ups, and dialogs in a Tkinter application. It is similar to the main Tkinter window (root), but it can be customized and managed separately.\r\nTo use the Toplevel widget, we need to import the Tkinter module and create an instance of the Toplevel class.\r\n

import tkinter as tk\r\n# create a Toplevel widget

top = tk.Toplevel()

This will create a new window with a default size and title. We can customize the window by setting its properties such as title, size, background color, and icon.\r\n# set the title of the window

top.title("My Window")\r\n# set the size of the window
top.geometry("300x200")\r\n# set the background color of the window
top.config(bg="white")\r\n# set the icon of the window
top.iconbitmap("icon.ico")

We can add widgets to the Toplevel window just like we do in the main Tkinter window (root).\r\n

# create a label widget
label = tk.Label(top, text="Hello, World!")
label.pack()

The pack() method is used to add the label widget to the window. We can also use the grid() or place() method to position the widgets in the Toplevel window.\r\nTo destroy or close the Toplevel window, we can use the destroy() method.\r\n# destroy the window

top.destroy()

Here's a full example of a Tkinter application that uses the Toplevel widget:\r\n

import tkinter as tk\r\n# create the main window

root = tk.Tk()\r\n# set the title of the main window
root.title("My App")\r\n# create a button that opens a new window
def open_window():
    top = tk.Toplevel()
    top.title("New Window")
    top.geometry("300x200")
    top.config(bg="white")
    label = tk.Label(top, text="Hello, World!")
    label.pack()
    close_button = tk.Button(top, text="Close Window", command=top.destroy)
    close_button.pack()\r\n# create a button in the main window
button = tk.Button(root, text="Open Window", command=open_window)
button.pack()\r\n# start the main event loop
root.mainloop()

This program creates a main window with a button that opens a new window (Toplevel widget) when clicked. The new window contains a label and a button to close the window.