How to bind the Escape key to close a window in Tkinter?

Tkinter Events are very useful for making an application interactive and functional. It provides a way to interact with the internal functionality of the application and helps them to rise whenever we perform a Click or Keypress event.

In order to schedule the events in tkinter, we generally use the bind('Button', callback) method. We can bind any key to perform certain tasks or events in the application. To bind the Esc key such that it will close the application window, we have to pass the Key and a callback event as the parameter in the bind(key, callback) method.


# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the tkinter window

# Define the style for combobox widget
style = ttk.Style()

# Define an event to close the window
def close_win(e):
# Add a label widget
label = ttk.Label(win, text="Eat, Sleep, Code and Repeat", font=('Times New Roman italic', 18), background="black", foreground="white"), rely=.5, anchor=CENTER)
ttk.Label(win, text="Now Press the ESC Key to close this window", font=('Aerial 11')).pack(pady=10)

# Bind the ESC key with the callback function
win.bind('<Escape>', lambda e: close_win(e))



Running the above code will display a window which can be closed immediately by pressing the "Esc" Key.

Now press the <Esc> key to close the window.

Updated on: 08-Jun-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started