Home > Software design >  How get name of Toplevel window of another Toplevel?
How get name of Toplevel window of another Toplevel?

Time:10-29

import tkinter as tk


r = tk.Tk()
r.title("root")
r.geometry("200x200")
f =tk.Frame(r)
f.pack()

top1 = tk.Toplevel(f)
top1.title("A")
#some widgets inside top2

top2 = tk.Toplevel(top1)
top2.title("B")  

print(top1.winfo_toplevel(), top1.winfo_children())

r.mainloop()

I only want to get the toplevel of top1 and nothing else i.e .!frame.!toplevel.!toplevel

winfo_toplevel() returns .!frame.!toplevel

winfo_children() returns .!frame.!toplevel.!toplevel, ... all children

CodePudding user response:

Your question is a bit unclear, but what I think you're asking is how to get top2 given only top1.

There's no direct way to do that. You can get all of the children of top1 and then return any children that are Toplevel widgets. If you know that top1 only has a single child that is a Toplevel, you can then return the first child that is a Toplevel.

def get_toplevel(w):
    for child in w.winfo_children():
        if child.winfo_class() == "Toplevel":
            return child
    raise Exception("No toplevel window was found")
  • Related