Reputation: 75
When I typed the following code as per the Think Python text book, I'm getting the error message below.
The window does actually get displayed, but it doesn't contain the desired content.
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')
The error message was like this:
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
Upvotes: 0
Views: 647
Reputation: 32590
The main application loop needs to be pretty much the last thing you run in your application. So move world.mainloop()
to the end of your code like this:
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()
What happens in your code is that when the line with world.mainloop()
is hit, it builds the user interface elements and goes in to the main loop, which continuously provides your application with user input.
During it's lifetime, that main loop is where your application will spend 99% of its time.
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.
Upvotes: 3