<p>您可以创建一个扩展Tkinter<code>Button</code>类的类,该类将通过将<code>destroy</code>方法与其<code>command</code>属性关联来专门关闭窗口:</p>
<pre><code>from tkinter import *
class quitButton(Button):
def __init__(self, parent):
Button.__init__(self, parent)
self['text'] = 'Good Bye'
# Command to close the window (the destory method)
self['command'] = parent.destroy
self.pack(side=BOTTOM)
root = Tk()
quitButton(root)
mainloop()
</code></pre>
<p>这是输出:</p>
<p><img src="https://i.stack.imgur.com/yzWVO.png" alt="enter image description here"/></p>
<hr/>
<p>以及之前代码不起作用的原因:</p>
<pre><code>def close_window ():
# root.destroy()
window.destroy()
</code></pre>
<p>我有一种轻微的感觉,你可能从其他地方得到根,因为你做了<code>window = tk()</code>。</p>
<p>当您对Tkinter中的<code>window</code>调用destroy意味着销毁整个应用程序,因为您的<code>window</code>(根窗口)是应用程序的主窗口。我想你应该把<code>window</code>改成<code>root</code>。</p>
<pre><code>from tkinter import *
def close_window():
root.destroy() # destroying the main window
root = Tk()
frame = Frame(root)
frame.pack()
button = Button(frame)
button['text'] ="Good-bye."
button['command'] = close_window
button.pack()
mainloop()
</code></pre>