[Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter?

Alan Gauld alan.gauld at yahoo.co.uk
Fri Aug 28 03:48:22 EDT 2020


On 28/08/2020 02:34, boB Stepp wrote:

> 3.8.3:  import tkinter as tk
> 3.8.3:  window = tk.Tk()
> 
> A tkinter window opens despite there being no explicit call to
> window.mainloop().  Why is this so?

Because it's what Tcl/Tk does...

> And even more interesting (and useful) I can see the execution of a
> tkinter window being built widget by widget

I've always assumed that's why the window appears when it does:
so that you can see the widgets as you add them when
working interactively. But I confess I have never investigated
deeply, its just a handy feature!

> I am greatly looking forward to someone's explanation of why all of
> this works without an explicit call to window.mainloop().

mainloop() turns on the event handling, until then the window
is just a graphic image on screen. But you don't need the
mainloop running to draw on the screen, its only when you
want to interact with it that you have to start mainloop().

Note that this behaviour depends on the environment. If you
use a shell within an IDE it might not happen, but if you
use a shell from the OS it will (IDLE works like this too).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list