[Tkinter-discuss] the difference between mainloop and app.mainloop and root.mainloop?

Michael Lange klappnase at web.de
Wed Aug 24 10:39:53 CEST 2011


Hi,

Thus spoketh "守株待兔" <1248283536 at qq.com> 
unto us on Wed, 24 Aug 2011 10:49:06 +0800:


(...)
> code1,code2.code3 all can run ,
> 
> what's the difference between mainloop and app.mainloop and
> root.mainloop? do they have different meaning?which one is right  in
> code1,code2,code3??

If you want to know things like this, the code from Tkinter.py might be a
good source ;)

So let's have a look at the methods' definitions; if you search
Tkinter.py for "def mainloop" you will find two matches:

1. Tkinter.mainloop():

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

(remember, _default_root is in fact the application's Tk() instance)

2. Tkinter.Misc.mainloop():

    def mainloop(self, n=0):
        """Call the mainloop of Tk."""
        self.tk.mainloop(n)

That is which both the Tk and the Frame class inherit from.

So you see that calls to root.mainloop() and mainloop() are equivalent,
behind the scene both will call:

	your_tk_instance.tk.mainloop()

Apparently the case is slightly different when you do call app.mainloop(),
because then of course

	your_frame_instance.tk.mainloop()

is actually called.

So now the question is, if the Tk() and the Frame() widget's tk attribute
actually point to the same object. To test this, your friend is the
python prompt:

>>> from Tkinter import *
>>> root = Tk()
>>> f = Frame()
>>> root.tk == f.tk
True
>>> root.tk
<tkapp object at 0xf7115988>
>>> f.tk
<tkapp object at 0xf7115988>
>>> 

So you see, all Tkinter widgets share the same object as their tk
attribute and so in the end all the calls to mainloop() do exactly the
same.

I hope this helps

Michael


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

Time is fluid ... like a river with currents, eddies, backwash.
		-- Spock, "The City on the Edge of Forever", stardate
                   3134.0


More information about the Tkinter-discuss mailing list