根据Think Python教科书输入以下代码时,我收到以下错误消息。
实际上会显示窗口,但它不包含所需的内容。
from swampy.World import World
world=World()
world.mainloop()
canvas = world.ca(width=500, height=500, background='white')
bbox = [[-150,-100], [150, 100]]
canvas.rectangle(bbox, outline='black', width=2, fill='green4')
错误信息是这样的:
Traceback (most recent call last):
File "15.4.py", line 4, in <module>
canvas = world.ca(width=500, height=500, background='white')
File "/usr/local/lib/python2.7/dist-packages/swampy/Gui.py", line 244, in ca
return self.widget(GuiCanvas, width=width, height=height, **options)
File "/usr/local/lib/python2.7/dist-packages/swampy/Gui.py", line 359, in widget
widget = constructor(self.frame, **widopt)
File "/usr/local/lib/python2.7/dist-packages/swampy/Gui.py", line 612, in __init__
Tkinter.Canvas.__init__(self, w, **options)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 2234, in __init__
Widget.__init__(self, master, 'canvas', cnf, kw)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 2094, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: can't invoke "canvas" command: application has been destroyed
答案 0 :(得分:3)
主应用程序循环几乎是您在应用程序中运行的最后一件事。所以将world.mainloop()
移到代码的末尾,如下所示:
from swampy.World import World
world = World()
canvas = world.ca(width=500, height=500, background='white')
bbox = [[-150, -100], [150, 100]]
canvas.rectangle(bbox, outline='black', width=2, fill='green4')
world.mainloop()
代码中发生的情况是,当命中world.mainloop()
的行时,它会构建用户界面元素并进入主循环,从而不断为应用程序提供用户输入。
在其生命周期中,该主循环是您的应用程序将花费99%的时间。
但是一旦你退出你的应用程序,主循环终止并拆除所有这些用户界面元素和世界。然后执行主循环后的剩余行。在那些中,您正在尝试构建并将画布附加到已经被销毁的世界,因此出现错误消息。