can't invoke "canvas" command: application has been destroyed
<p>When I typed the following code as per the <a href="http://greenteapress.com/wp/think-python/" rel="nofollow">Think Python</a> text book, I'm getting the error message below.</p>

<p>The window does actually get displayed, but it doesn't contain the desired content.</p>

<pre><code>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')
</code></pre>

<p>The error message was like this:</p>

<pre><code>Traceback (most recent call last):
  File "15.4.py", line 4, in &lt;module&gt;
    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
</code></pre>

<p>The main application loop needs to be pretty much the last thing you run in your application. So move <code>world.mainloop()</code> to the end of your code like this:</p>

<pre><code>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()
</code></pre>

<p>What happens in your code is that when the line with <code>world.mainloop()</code> is hit, it builds the user interface elements and goes in to the main loop, which continuously provides your application with user input.</p>

<p>During it's lifetime, that main loop is where your application will spend 99% of its time.</p>

<p>But once you quit your application, the main loop terminates and tears down all those user interface elements and the world. Then the remaining lines after the main loop will be executed. In those, you're trying to build and attach a canvas to a world that has already been destroyed, hence the error message.</p>

python python-2.7 python-3.x