How to close a Tkinter window by pressing a Button?


Tkinter initially creates a window or frame that contains widgets and Labels within it. Let us suppose we want to close the tkinter window with a button. A Button is a UI widget that can be used to perform a certain operation.

Example

Here, we will create a button that closes the tkinter window. In order to close and terminate the TCL interpreter, we mainly use the destroy() method.

#Import the required libraries
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Set the geometry of frame
win.geometry("600x250")

#Create a Label
Label(win, text="Press the Close Button to close the window",
font=('Helvetica bold', 11)).pack(pady=20)
#Define a function to close the window
def close_win():
   win.destroy()

#Create a Button for closing the window
button= Button(win, text="Close", command=close_win)
button.pack(pady=20)

win.mainloop()

Output

Running the above code will display a window containing a button that can be triggered to close the window or frame.

Now click the “Close” button to close the window.

Updated on: 26-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements