How to exit from Python using a Tkinter Button?


To exit from Python using a Tkinter button, you can follow the steps given below −

Steps −

  • Import the tkinter library and create an instance of tkinter frame.

  • Set the size of the frame using geometry method.

  • Define a function close() to close the window. Call the method win.destroy() inside close().

  • Next, create a button and call the close() function.

  • Finally, run the mainloop of the application window.


# Import the library
from tkinter import *

# Create an instance of window
win = Tk()

# Set the geometry of the window

# Title of the window
win.title("Click the Button to Close the Window")

# Define a function to close the window
def close():

# Create a Button to call close()
Button(win, text= "Close the Window", font=("Calibri",14,"bold"), command=close).pack(pady=20)



On execution, it will produce the following output −

On clicking the button, it will close the window.

Instead of win.destroy(), you can also use win.quit() to close the application. However, there is a subtle difference between the two. win.quit() abruptly quits the application which means the mainloop will still be running in the background. win.destroy() on the other hand terminates the mainloop and destroys all the widgets inside the window.

Published on 26-Oct-2021 13:29:39