【问题标题】:Cannot invoke button command: application has been destroyed无法调用按钮命令:应用程序已被销毁
【发布时间】:2014-03-05 22:12:39
【问题描述】:

下面是使用 Tkinter 和 Python 创建独立窗口的代码:

import Tkinter

Tkinter.NoDefaultRoot()

win1=Tkinter.Tk()
win2=Tkinter.Tk()

Tkinter.Button(win1, text='Woho!',command=win1.destroy()).pack()
Tkinter.Button(win2, text='Woho!',command=win2.destroy()).pack()

win1.mainloop()

执行时显示:

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\eclipse\Python Projects\Project 1\Source1\mod.py", line 8, in <module>
    Tkinter.Button(win1, text='Woho!',command=win1.destroy()).pack()
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2106, in __init__
    Widget.__init__(self, master, 'button', cnf, kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2036, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: can't invoke "button" command:  application has been destroyed

我是 Python 新手,因此不明白它的含义。我哪里错了?

【问题讨论】:

  • Tkinter 并非设计用于运行两个 Tk 实例。如果您需要多个窗口,请创建一个 Tk 实例,然后再创建一个 Toplevel 实例。

标签: python python-2.7 user-interface tkinter tk


【解决方案1】:

win1.destroy()win2.destroy() 中删除()

Tkinter.Button(win1, text='Woho!',command=win1.destroy()).pack()
Tkinter.Button(win2, text='Woho!',command=win2.destroy()).pack()
                                                      ^^

它导致win1.destroy方法调用,并使用方法的返回值作为回调,而不是方法本身。在创建 Button 之前导致主窗口销毁。

Tkinter.Button(win1, text='Woho!',command=win1.destroy).pack()
Tkinter.Button(win2, text='Woho!',command=win2.destroy).pack()

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 1970-01-01
    • 2022-06-17
    • 2016-06-11
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多