Newbie question about Tkinter

Christopher T King squirrel at WPI.EDU
Mon Aug 16 11:33:41 EDT 2004


On 16 Aug 2004, Andr? Roberge wrote:

> The following program (Python 2.3, under Windows XP)
> ===
> import Tkinter as Tk
> A = Tk.Tk()
> A.title("1")
> A.mainloop()
> B = Tk.Tk()
> B.title("2")
> B.mainloop()
> ===
> opens window A and waits for it to be closed before opening window B.

For the record, you should only use Tk() once in your program; besides 
being the main top-level window, it also instantiates Tk and the Tcl 
interpreter.  If you want multiple top-level windows, use Tk() for the 
main one and Toplevel() for any additional ones.

> However, the following opens both windows "simultaneously".  I tought
> it would give the same result as the one above... I am confused.
> ====
> ====
> Anyone can explain or give a pointer to the answer.

Calling .mainloop() on any widget enters the "main event loop", which 
waits for keyboard/mouse events and dispatches them accordingly.  
.mainloop() typically doesn't return until the main top-level window (A or 
B in this case) is destroyed.  In the first example, you're calling 
A.mainloop() before creating B; hence A must be destroyed in order for 
A.mainloop() to exit.  Try each of the above in the interactive 
interpreter to see exactly what's going on (Tk works beautifully in an 
interactive mode).

Rewriting the above using Toplevel:

 import Tkinter as Tk
 A = Tk.Tk()
 A.title("1")
 B = Tk.Toplevel(A)
 B.title("2")
 A.mainloop()

Passing A as an argument to Toplevel (to specify its master) is optional; 
if you don't, Tkinter will automatically pick A as its master.




More information about the Python-list mailing list