[Tkinter-discuss] mainloop() problem

Michael Lange klappnase at web.de
Sat Aug 20 11:10:06 CEST 2011


Hi,

Thus spoketh "守株待兔" <1248283536 at qq.com> 
unto us on Sat, 20 Aug 2011 11:18:22 +0800:

(...)
> i don't know why  i  can't use mainloop()  instead  of  Demo().mainloop
> ()??
> 
> from Tkinter import *              # get base widget set
> from dialogTable import demos      # button callback handlers
> from quitter import Quitter        # attach a quit object to me
>     
> class Demo(Frame):
>     def __init__(self, parent=None):
>         Frame.__init__(self, parent)
>         self.pack()
>         Label(self, text="Basic demos").pack()
>         for (key, value) in demos.items():
>             Button(self, text=key, command=value).pack(side=TOP,
> fill=BOTH) Quitter(self).pack(side=TOP, fill=BOTH)
>     
> if __name__ == '__main__':
>     Demo().mainloop()   # you can't use  mainloop()


If you look at the error message you get when you try to call mainloop()
you will find valuable information:

Traceback (most recent call last):
  File "test7.py", line 16, in <module>
    mainloop()   # you can't use  mainloop()
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 328, in mainloop
    _default_root.tk.mainloop(n)
AttributeError: 'NoneType' object has no attribute 'tk'

So let's have a look at the Tkinter.mainloop() function:

def mainloop(n=0):
    """Run the main loop of Tcl."""
    _default_root.tk.mainloop(n)

To understand this, you need to know that Tkinter._default_root is an
internally used placeholder for the application's Tk() instance.
Initially _default_root is set to None, though. So effectively
Tkinter.mainloop () is just a shortcut to the Tk () window's (or any
other tk widget's) mainloop() method.

Considering this, it is easy to see why the call to mainloop() in your
example fails: you call mainloop() before any widget has been created and
so there is no _default_root yet.

I hope this helps

Michael



.-.. .. ...- .   .-.. --- -. --.   .- -. -..   .--. .-. --- ... .--. . .-.

I realize that command does have its fascination, even under
circumstances such as these, but I neither enjoy the idea of command
nor am I frightened of it.  It simply exists, and I will do whatever
logically needs to be done.
		-- Spock, "The Galileo Seven", stardate 2812.7


More information about the Tkinter-discuss mailing list