如何在Tkinter中获得主框架的名称

elj*_*bso 2 tkinter master widget frame


简而言之:Tkinter中是否有一个函数可以获取小部件的主框架的名称?

让我告诉您更多一点:
有一个名为“ BackButton”的按钮

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

当我单击此按钮时,有一个名为“ CloseFrame”的函数,它将关闭当前Frame(并执行其他操作),在本例中为“ SCPIFrame”。但是为此,我需要其中存在BackButton的Frame的名称。有任何想法吗?感谢您的帮助。

Ben*_*tch 9

我认为最好的方法是使用 .master 属性,它实际上是 master 的实例 :) 例如(我在 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 ;) 
Run Code Online (Sandbox Code Playgroud)


Fab*_*dre 5

要从字面上回答您的问题:

在Tkinter中是否有获取小部件主框架名称的函数?

winfo_parent正是您所需要的。为了有用,您可以将其与_nametowidget(结合使用)一起使用(因为winfo_parent实际上会返回父项的名称)。

parent_name = widget.winfo_parent()
parent = widget._nametowidget(parent_name)
Run Code Online (Sandbox Code Playgroud)