【问题标题】:Fix for "TclError: can't invoke "button" command"?修复“TclError:无法调用”按钮“命令”?
【发布时间】: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() 的调用返回,因此出现错误。将语句放在脚本的末尾。
  • 现在可以使用了!谢谢!!

标签: python tkinter button


【解决方案1】:

正确的代码是:

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. 主循环应该是捕获事件的最后一行(为了简单起见)

【讨论】:

  • 谢谢! @Corralien
猜你喜欢
  • 2022-06-17
  • 2019-01-29
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-03
  • 2019-06-15
  • 2014-03-05
相关资源
最近更新 更多