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

TkinterPythonGUI-Programming

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.

Example

# 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
win.geometry("700x350")

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

# Define an event to close the window
def close_win(e):
   win.destroy()
# Add a label widget
label = ttk.Label(win, text="Eat, Sleep, Code and Repeat", font=('Times New Roman italic', 18), background="black", foreground="white")
label.place(relx=.5, 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))

win.mainloop()

Output

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.

raja
Published on 08-Jun-2021 10:05:53
Advertisements