获取tkinter中顶级窗口的数量

2024-04-25 16:44:33 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法获得tkinter中顶级窗口的数量

代码如下:

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()

在这里,当我单击get_button时,我想打印顶级窗口的数量(在本例中为三个)

在tkinter有没有办法做到这一点

如果有人能帮我,那就太好了


Tags: of代码fromimportnumberget数量tkinter
3条回答

这对我有用

from tkinter import *

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

count = 0 #Total count of Toplevels
def get_number_of_toplevel_windows(ventana):
    global count
    for a,b in ventana.children.items(): #Getting list of root window's children and using recursion 
        if isinstance(b, Toplevel):
            count+=1 #If toplevel then count += 1
        get_number_of_toplevel_windows(b)

def printresult():
    print(count)
get_button = Button(root , text = "Get number of toplevel windows" , command = printresult)
get_button.pack()
get_number_of_toplevel_windows(root)
root.mainloop()

此解决方案仅适用于Windows平台(需要pywinauto库):

import tkinter as tk
from pywinauto import Desktop

NAME = 'Program name'

def get_number_of_toplevel_windows():
    windows = Desktop(backend='uia').windows()
    print(len([w.window_text() for w in windows if w.window_text() == NAME])-1)

root = tk.Tk()
root.title(NAME)
tk.Toplevel(root)
tk.Toplevel(root)
tk.Toplevel(root)
tk.Button(root, text='Get number of toplevel windows', command=get_number_of_toplevel_windows).pack()
tk.mainloop()

输出:

3

您可以使用winfo_children()调出所有子级,然后检查其中的“toplevel”,如:

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

这也不需要任何外部模块

或者:

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

后一种方法似乎更有效,因为它检查项的实例,并且不像第一种方法那样比较字符串

相关问题 更多 >