What's the difference between tkinter's Tk and Toplevel classes?
Asked Answered
T

1

24

In Python 3, I run the following from the interactive shell:

>>> import tkinter
>>> type(tkinter.Tk())
<class 'tkinter.Tk'>
>>> type(tkinter.Toplevel())
<class 'tkinter.Toplevel'>

Both of these create individual windows. I assume that tkinter.Tk() returns the "main" window of the tkinter app, while any additional windows should be created with tkinter.Toplevel().

I noted that if you close tkinter.Tk()'s window, both windows close. Also, if you call tkinter.Toplevel() without a call to tkinter.Tk(), two windows are created (one of them being the "main" window that, when closed, will also close the Toplevel window).

Is this accurate? Are there any other differences that I should be concerned with?

Thaliathalidomide answered 15/4, 2015 at 16:2 Comment(1)
At a base level: Tk is the whole app and Toplevel is just a window.Lenorelenox
V
24

Your summary is accurate. One of tkinter's core architectural features is that the widgets exist in a hierarchy with exactly one root window. That root window is what you get when you instantiate Tk.

Instantiating Tk does more than create a window, it initializes the entire tkinter framework. It actually starts up a hidden tcl interpreter which does the actual work of managing widgets. Tkinter is just a python wrapper around this interpreter.

If you attempt to create some other widget without explicitly creating a root window first, one will be created automatically since every tkinter application must have exactly one root window.

Vamp answered 15/4, 2015 at 16:28 Comment(1)
One can add that you can actually use that hidden Tcl interpreter via the tkinter.Tcl() method without creating any windows, but that would be a rare sight in Python land. (it is a silly way to sidestep the python GIL as the Tcl interpreter has no GIL and might support threading).Vargas

© 2022 - 2024 — McMap. All rights reserved.