我如何绑定转义键来关闭这个 window

How do I bind the escape key to close this window

我拼凑了一个小程序来下载专利。我想将转义键绑定到一个函数以关闭 window,但我真的不知道如何实现。我已经将转义键绑定到 "quit" 函数,但是有人可以帮我弄清楚如何编写函数来关闭文本输入 window 吗?

我是菜鸟

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()

编辑:这是新错误:

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

首先,quit 是一个内置方法,所以我会使用另一个名称。否则,函数如下:

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)

你应该使用比sys.exit()更安全的退出方法。在我的示例中,root.destroy() 是一种安全、可靠的退出 Tkinter 应用程序的方法。 destroy() 只是终止主循环并删除所有小部件。因此,如果您从另一个 Tkinter 应用程序调用您的应用程序,或者如果您有多个主循环,似乎会更安全。

import tkinter as tk

def exit(event):
    root.destroy()

root = tk.Tk()

root.bind("<Escape>", exit)
root.mainloop()

您可以在 lambda 表达式中使用 destroy() 方法来安全退出。我在 python 3.7.x.

中使用过
import tkinter as tk
root = tk.Tk()
root.bind("<Escape>", lambda x: root.destroy())
root.mainloop()