How to close only the TopLevel window in Python Tkinter?


The Toplevel window is an option to create a child window in an application. It works similar to the default main tkinter window. We can configure the size of a Toplevel window, customize its properties and attributes as well as add widgets that we want to build the component with.

For a particular application, if we have defined a Toplevel window, then we can close it using the destroy() method.

Example

In the following example, we have created an application that contains a button to open a Toplevel window. The Toplevel window or child window contains a label text and a button to close the corresponding window. Whenever the button is clicked, the Toplevel window gets closed.

# Import required libraries
from tkinter import *

# Create an instance of tkinter window
win = Tk()
win.geometry("700x400")
win.title("Root Window")

# Function to create a toplevel window
def create_top():
   top=Toplevel(win)
   top.geometry("400x250")
   top.title("Toplevel Window")
   Label(top, text="Hello, Welcome to Tutorialspoint", font='Arial 15 bold').pack()

   # Button to close the toplevel window
   button=Button(top, text="Close", command=top.destroy)
   button.pack()

# Create a button to open the toplevel window
button=Button(win, text="Click Here", font='Helvetica 15', command=create_top)
button.pack(pady=30)

win.mainloop()

Output

Running the above code will display a window containing a button that opens a Toplevel window.

Once the Toplevel is opened, you can click the button "close" to close the toplevel window.

Updated on: 22-Dec-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements