python - 获取 tkinter 中顶层窗口的数量
问题描述
有什么方法可以获取 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 中实现这一点?
如果有人可以帮助我,那就太好了。
解决方案
您可以只使用winfo_children()
来抚养所有孩子,然后检查其中的“顶层”,例如:
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
后一种方法似乎更有效,因为它检查项目的实例并且不像第一种方法那样比较字符串。
推荐阅读
- python-3.x - 当对象很大时 pool.map 冻结
- python - 使用 pandas 将列附加到列
- c# - 控制请求对象解构的选项
- swift - 具有类绑定约束的泛型类不能通过类绑定协议参数化
- python - 如何创建逻辑来在熊猫中进行值映射?
- python - 为什么我的熊猫数据框使用这么多内存?
- elixir - 在 Elixir 中,将测试文件与相关模块放在一起
- c# - Angular:无法通过 HttpResponse 返回自定义错误消息
- c# - 在分支之间转换时生成错误:您的项目未引用“.NETFramework,Version=v4.7.2”框架
- python - 抓取linkedin新闻提要