I have a little program that I've cobbled together to download patents. I'd like to bind the escape key to a function to close the window, but I don't really know how to make this happen. I've bound the escape key to a "quit" function, but can someone help me figure out how to write the function to close the text input window?
I'm a noob.
from Tkinter import *
import urllib
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
def patdload(self, event=None):
allnums = e.get()
index = 0
test = allnums.find('.')
if test > 0:
sep = 0
while sep != -1:
sep = allnums.find('.', index)
if sep != -1:
patno = allnums[index:sep]
elif sep == -1:
patno = allnums[index:]
#patno = e.get()
paturl = "http://patentimages.storage.googleapis.com/pdfs/US" + patno + ".pdf"
urllib.urlretrieve (paturl, (patno + ".pdf"))
index = sep + 1
else:
patno = e.get()
paturl = "http://patentimages.storage.googleapis.com/pdfs/US" + patno + ".pdf"
urllib.urlretrieve (paturl, (patno + ".pdf"))
def quit #help#:
master.bind('<Return>', patdload)
master.bind('<Escape>',quit)
#b = Button(master, text = "GET", width = 10, command = patdload)
#b.pack()
mainloop()
Edit: here's the new error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:\Python27\PatentGet.py", line 42, in <lambda>
master.bind('<Escape>', lambda x: close())
File "C:\Python27\PatentGet.py", line 39, in close
master.widthdraw() # if you want to bring it back
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1894, in __getattr__
return getattr(self.tk, attr)
AttributeError: widthdraw
click where it says menu and lists the keybinding as escape. You will be prompted to rebind it to a different key. Then go to the setting you wish to bind the escape key to. If you accidentally unbound it from the menu, then go to to the on foot tab, look for menu, and rebind it to the escape key.
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.
Avoiding the Esc key If you have an American English keyboard, pressing Ctrl-[ (control plus left square bracket) is equivalent to pressing Esc.
1. Short for Escape, Esc is a key found on the top-left corner of a computer keyboard. It allows the user to abort, cancel, or close an operation.
First of all, quit is a built-in method so I'd use another name. Otherwise, here's the function:
import sys
def close(event):
master.withdraw() # if you want to bring it back
sys.exit() # if you want to exit the entire thing
master.bind('<Escape>', close)
You can use destroy()
method within lambda expression to safely exit. I have used in python 3.7.x
.
import tkinter as tk
root = tk.Tk()
root.bind("<Escape>", lambda x: root.destroy())
root.mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With