Tkinter: why do both windows open?
<p>I started looking at some Tkinter tutorials. I always like to mess around with code before going on with the next chapter: for instance I tried to open more than one independent root.</p>

<pre><code>from Tkinter import *

def main():
    root1, root2 = Tk(), Tk()
    root1.title("First window")
    root2.title("Second window")
    root1.mainloop()
    root2.mainloop()

main()
</code></pre>

<p>What I don't understand is why this code works (i.e. it shows two different windows at the same time).
If the Tk "mainloop" method is a loop, why do I see the second window? Shouldn't I see it only after closing the first window (i.e. after breaking the first while loop)?</p>

<p>Please, explain me how it works</p>

<p><strong>EDIT: Removed incorrect answer, added answer below</strong></p>

<p>The short of why are confused is that the behavior of your code is undefined. Really, it isn't running as differently as you think. Try running this code:</p>

<pre><code>from Tkinter import *

def main():
    root1, root2 = Tk(), Tk()
    root1.title("First window")
    root2.title("Second window")

    root1.mainloop()
    print 'root1.mainloop() has finished running.'
    root2.mainloop()
    print 'root2.mainloop() has finished running.'

main()
</code></pre>

<p>So the first <code>mainloop</code> doesn't actually continue on immediately. It hangs on <code>root1.mainloop()</code> (as you expected) until you close both of the windows, then it continues on. I am not sure exactly why running <code>root1.mainloop()</code> opens both windows as I don't have access to all of the source code but I think it would be a little bit like asking about the results of <code>0/0</code>. It just isn't supposed to happen. </p>

python loops methods tkinter