Bind Escape to Exit

Kent Johnson kent37 at tds.net
Sun Mar 13 08:23:58 EST 2005


Binny V A wrote:
> Hello Everyone,
> 
> I am new to python and I am trying to get a program 
> to close a application when the Escape Key is pressed.

Here is a version that works. The changes from yours:
- Bind <Escape>, not <Key-Escape>
- Bind the key to the root, not the frame
- Define a quit() method that takes an event parameter

from Tkinter import *

class Application(Frame):
     def createWidgets(self):
         self.lab = Label(text="Hello World")
         self.lab.pack()

     def __init__(self, master=None):
         Frame.__init__(self, master)
         self.pack()
         self.createWidgets()
         master.bind('<Escape>',self.quit)

     def quit(self, event):
         Frame.quit(self)

root=Tk()
app = Application(root)
app.mainloop()


Kent

> 
> This is the code that I used
> 
> ---------------------------------
> from Tkinter import *
> 
> class Application(Frame):
> 	def createWidgets(self):
> 		self.lab = Label(text="Hello World")
> 		self.lab.pack()
> 		
> 	def __init__(self, master=None):
> 		Frame.__init__(self, master)
> 		self.pack()
> 		self.createWidgets()
> 		self.bind('<Key-Escape>',self.quit)
> 
> app = Application()
> app.mainloop()
> 
> ---------------------------------
> 
> It is displaying everything properly, but it is not quiting
> when the escape key is pressed.



More information about the Python-list mailing list