How do I close a window in tkinter?
root.destroy() closes the window and ends the program. It is what you want almost every time.
import tkinter as tk
root = tk.Tk()
tk.Button(root, text="Quit", command=root.destroy).pack()
root.mainloop() destroy() versus quit()
destroy() tears the windows down and then lets mainloop() return. quit() only stops the loop — the widgets still exist, so if anything runs after mainloop() you can end up with a program that appears closed but has not exited, which is the source of the "my script hangs on close" question.
Use destroy(). Reach for quit() only when you deliberately want to leave the loop and carry on doing something with the widgets still alive, which is rare.
Closing a second window only
Calling destroy() on a Toplevel closes just that window and leaves the app running. Inside a class it is self.root.destroy(), where self.root is the Toplevel — a good reason to keep the reference.
settings_window.destroy() # the app keeps goingAsking "are you sure?" when they click the X
The window manager's close button does not go through your button. Intercept it with the WM_DELETE_WINDOW protocol, and you get the chance to confirm or save first.
from tkinter import messagebox
def on_close():
if messagebox.askokcancel("Quit", "Close without saving?"):
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_close) Doing it without the lookup
A Quit button is a button with its command set to self.root.destroy, and a menu item can do the same. If you want the confirm-on-close behaviour, the generated class is a normal Python class — the protocol() line goes in __init__ and survives re-import.
Lay the window out visually and read the generated Python as you go.
Open the tkinter designer →