- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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.
- Related Articles
- How to bind the Enter key to a tkinter window?
- How to bind a key to a button in Tkinter?
- Function to close the window in Tkinter
- How to bind the spacebar key to a certain method in Tkinter?
- How to close only the TopLevel window in Python Tkinter?
- How to close a Tkinter window by pressing a Button?
- How do I bind the enter key to a function in Tkinter?
- How do I close a tkinter window?
- How do I handle the window close event in Tkinter?
- Automatically close window after a certain time in Tkinter
- How to bind multiple events with one "bind" in Tkinter?
- How to bind to shift+tab in Tkinter?
- How to bind a click event to a Canvas in Tkinter?
- How to bind all the number keys in Tkinter?
- Tkinter-How to get the current date to display in a tkinter window?

Advertisements