【发布时间】:2021-12-28 23:19:18
【问题描述】:
我第一次在 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()
它应该创建一个带有按钮的窗口,但我只收到错误消息:
---------------------------------------------------------------------------
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.
【问题讨论】:
-
fenetre.mainloop()应该出现在代码的末尾,而不是介于两者之间。mainloop()下面的代码仅在退出 GUI 时运行。 -
tkinter 窗口关闭时,对
fenetre.mainloop()的调用返回,因此出现错误。将语句放在脚本的末尾。 -
现在可以使用了!谢谢!!