Fix for "TclError: can't invoke "button" command"?

Fix for "TclError: can't invoke "button" command"?

我第一次尝试在 python 中使用 tkinter,但是 Button 命令产生了一个错误

from tkinter import *
fenetre=Tk()
label=Label(fenetre,text="Hello World ! ")
label.pack() 
fenetre.mainloop()
bouton=Button(fenetre,text="fermer", command=fenetre.quit)
boutoun.pack()

它应该创建一个带有按钮的 window,但我只收到错误消息:

---------------------------------------------------------------------------
TclError                                  Traceback (most recent call last)
<ipython-input-21-fd57f3be1272> in <module>
----> 1 bouton=Button(fenetre,text="Exit !", command=fenetre.quit)
      2 boutoun.pack()

~\anaconda3\lib\tkinter\__init__.py in __init__(self, master, cnf, **kw)
   2648             overrelief, state, width
   2649         """
-> 2650         Widget.__init__(self, master, 'button', cnf, kw)
   2651 
   2652     def flash(self):

~\anaconda3\lib\tkinter\__init__.py in __init__(self, master, widgetName, cnf, kw, extra)
   2570         for k, v in classes:
   2571             del cnf[k]
-> 2572         self.tk.call(
   2573             (widgetName, self._w) + extra + self._options(cnf))
   2574         for k, v in classes:

TclError: can't invoke "button" command: application has been destroyed```
There's some similar questions in the forum but unfortunately they do not work for me.

正确的代码是:

from tkinter import *
fenetre=Tk()
label=Label(fenetre,text="Hello World ! ")
label.pack() 
bouton=Button(fenetre,text="fermer", command=fenetre.destroy)  # HERE (1)
bouton.pack()
fenetre.mainloop()  # HERE (2)
  1. 使用fenetre.destroy代替fenetre.quit
  2. 主循环应该是最后一行捕捉事件(为了简单)