Is it necessary to call Tk() when writing a GUI app with Tkinter?

John Salerno johnjsal at gmail.com
Wed Feb 29 00:06:41 EST 2012


The book I'm reading about using Tkinter only does this when creating the top-level window:

app = Application()
app.mainloop()

and of course the Application class has subclassed the tkinter.Frame class.

However, in the Python documentation, I see this:

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

Is it necessary to explicitly call Tk(), then pass that result as an argument for the Application call? Is it also necessary to call destroy() on the root frame?

I tried the above and I got the following error:

Traceback (most recent call last):
  File "C:\Users\John\Desktop\gui.py", line 12, in <module>
    root.destroy()
  File "C:\Python32\lib\tkinter\__init__.py", line 1714, in destroy
    self.tk.call('destroy', self._w)
_tkinter.TclError: can't invoke "destroy" command:  application has been destroyed

So apparently closing the window with the X button (on Windows) implicitly calls the destroy() method of the root frame. If that's the case, why does the documentation explicitly call it?

Furthermore, I pasted the exact example from the documentation into IDLE and ran it, and I also go the same error, so the example in the documentation doesn't even work.

So is it sufficient simply to create an Application instance, use mainloop, and then handle the closing of the window elsewhere in the program (such as a widget calling the destroy method on-click, or just letting the X button do it)?

Thanks!



More information about the Python-list mailing list