⊕
⊖
Contents
Tkinter – Close window on Escape key stroke
In Tkinter, you can bind the Escape key stroke to close a window.
To close the window in Tkinter when user hits Escape key, bind the Escape key event with the window, and specify a lambda function that closes this window.
window.bind('<Escape>', lambda e, w=window: w.destroy())
In this tutorial, you will learn how to bind Escape key stroke to closing the window in Tkinter, with example.
Examples
1. Close window when user hits Escape key
In this example, we create a basic Tk window, and then call bind() method on this window to bind the Escape key with the closing of the window.
Python Program
import tkinter as tk
# Create the main window
window = tk.Tk()
window.title("PythonExamples.org")
window.geometry("300x200")
label = tk.Label(window, text="Press Escape key on keyboard to close this window.")
label.pack()
# Bind Escape key to close window
window.bind('<Escape>', lambda e, w=window: w.destroy())
# Run the application
window.mainloop()
Output
In Windows
In MacOS
If you press Escape key, the window closes.
Summary
In this Python Tkinter tutorial, we learned how to bind Escape key to the window in Tkinter, to close the window when user presses Escape key in keyboard, with examples.