How to get the name of the Master Frame in Tkinter

eljobso picture eljobso · Oct 15, 2012 · Viewed 9.6k times · Source


to cut a long story short: Is there a function to get the name of the Master Frame of a widget in Tkinter?

Let me tell you a little bit more:
There is a Button, named "BackButton"

self.BackButton = Button(self.SCPIFrame, text = "Back", command = self.CloseFrame)
self.BackButton.place(x = 320, y = 320, anchor = CENTER)

When I click on this Button, there is a function named "CloseFrame", which closes the current Frame (and doing some other stuff), in this case "SCPIFrame". But for this, I need the name of the Frame, in which the BackButton is present. Any ideas? Thanks for helping.

Answer

Benkevitch picture Benkevitch · Feb 23, 2017

I think the best way is to use the .master attribute, which is literally the master's instance :) For example (I am doing this in IPython):

import Tkinter as tk

# We organize a 3-level widget hierarchy:
# root
#   frame
#     button

root = tk.Tk()
frame = tk.Frame(root)    
frame.pack()
button = tk.Button(frame, text="Privet!", background='tan')
button.pack()

# Now, let's try to access all the ancestors 
# of the "grandson" button:

button.master   # Father of the button is the frame instance:
<Tkinter.Frame instance at 0x7f47e9c22128>

button.master.master   # Grandfather of the button, root, is the frame's father:
<Tkinter.Tk instance at 0x7f47e9c0def0>

button.master.master.master  # Empty result - the button has no great-grand-father ;)