pythontkintertoplevel

Get list of Toplevels on Tkinter


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?


Solution

  • 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