Get list of Toplevels on Tkinter

╄→尐↘猪︶ㄣ 提交于 2021-01-29 02:12:50

问题


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:


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


来源:https://stackoverflow.com/questions/60978666/get-list-of-toplevels-on-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!