1
votes

I wanted to know if there is a simple way to get all the toplevels from a specific window, including toplevels within toplevels. In the following code I leave an example of what I want to do:

from tkinter import Tk, Toplevel

v = Tk()
v2 = Toplevel(v)
v3 = Toplevel(v2)
v4 = Toplevel(v2)

def toplevels(ventana):
    print("Here I return the list of all toplevels, in case of choosing the main window, it should return:")
    print()
    print(".")
    print(".toplevel")
    print(".toplevel.toplevel")
    print(".toplevel.toplevel2")

toplevels(v)

Is there something built into Tkinter to accomplish this?

1
create list at start and manually append() every Toplevel to this list. all_toplevels.append(v) - furas
The function I'm looking for was meant to be put into a module, but I might use your idea as a last resort. Thank you. - Dante S.
every widget has list of childen widgets so you could get this list and check type of every child. And you would have to use recursion to check every child inside every item. - furas
True, but the function you say (winfo_children) does not return all toplevels, only the toplevels associated with the window. For example v.winfo_children () will return only to v2, not v3 and v4. - Dante S.
About recursion, that's what I'm trying to see. What I was asking was if there was a simpler method. - Dante S.

1 Answers

3
votes

Every widget has list of its children and using recursion you can get all widgets.

from tkinter import Tk, Toplevel, Label

v = Tk()
v2 = Toplevel(v)
v3 = Toplevel(v2)
v4 = Toplevel(v2)
Label(v)
Label(v2)
Label(v3)
Label(v4)

def toplevels(ventana):
    for k, v in ventana.children.items():
        if isinstance(v, Toplevel):
            print('Toplevel:', k, v)
        else:
            print('   other:', k, v)
        toplevels(v)

toplevels(v)

Result

Toplevel: !toplevel .!toplevel
Toplevel: !toplevel .!toplevel.!toplevel
   other: !label .!toplevel.!toplevel.!label
Toplevel: !toplevel2 .!toplevel.!toplevel2
   other: !label .!toplevel.!toplevel2.!label
   other: !label .!toplevel.!label
   other: !label .!label