Tkinter – Close window programmatically

Tkinter – Close window programmatically

In Tkinter, you can close a window programmatically by using Tk.destroy() method.

Tkinter - Close window programmatically
Tkinter – Press button to close window programmatically

To close a window in Tkinter programmatically, call destroy method on the Tk class object which is our window.

window = tk.Tk()
window.destroy()

In this tutorial, you will learn how to programmatically close the window in Tkinter, with examples.

Examples

1. Close window on Button click

In this example, we create a basic Tk window with a button in it. When user clicks on this button, we close the window using destroy() method.

Python Program

import tkinter as tk

# Create the main window
window = tk.Tk()
window.title("PythonExamples.org")
window.geometry("300x200")

def button_click():
    window.destroy()

# Create a button
button = tk.Button(window, text="Close window", command=button_click)
button.pack()

# Run the application
window.mainloop()

Output

In Windows

In MacOS

Tkinter - Close window programmatically
Tkinter – Press button to close window programmatically

If you press Close window button, the window.destroy() method is called, and the window is closed.

Summary

In this Python Tkinter tutorial, we learned how to close the window programmatically using Tk.destroy() method, with examples.

Code copied to clipboard successfully 👍