Search code examples
pythontkintertoplevel

Get the number of Toplevel windows in tkinter


Is there any way to get the number of toplevel windows in tkinter?

Here's the code:

from tkinter import *

root = Tk()
root.geometry("500x500")

def get_number_of_toplevel_windows():
    # Code to count the number of toplevel windows
    pass

toplevel_1 = Toplevel(root)
toplevel_2 = Toplevel(root)
toplevel_3 = Toplevel(root)

get_button = Button(root , text = "Get number of toplevel windows" , command = get_number_of_toplevel_windows)
get_button.pack()

mainloop()

Here when I click on the get_button, I want to print the number of toplevel windows (three in this case.).

Is there any way to achieve this in tkinter?

It would be great if anyone could help me out.


Solution

  • You could just use winfo_children() to bring up all the children and then check for 'toplevel' inside it, like:

    def get_number_of_toplevel_windows():
        tops = [] # Empty list for appending each toplevel
        for widget in root.winfo_children(): # Looping through widgets in main window
            if '!toplevel' in str(widget): # If toplevel exists in the item
                tops.append(widget) # Append it to the list
                 
        print(len(tops)) # Get the number of items in the list, AKA total toplevels
    

    This does not require any external modules too.

    Or alternatively:

    def get_number_of_toplevel_windows():
        tops = []
        for widget in root.winfo_children(): # Loop through each widget in main window
            if isinstance(widget,Toplevel): # If widget is an instance of toplevel
                tops.append(widget) # Append to a list
                 
        print(len(tops)) # Get the number of items in the list, AKA number of toplevels
    

    The latter method seems to be more efficient as it checks the instance of items and does not compare strings like the first method.

    Update:

    OR use this one-liner:

    get_number_of_toplevel_windows = lambda root: len([x for x in root.winfo_children() if isinstance(x , Toplevel)])
    
    # Usage
    toplevels = get_number_of_toplevel_windows(root) # 3