【问题标题】:How to get the name of the Master Frame in Tkinter如何在 Tkinter 中获取主框架的名称
【发布时间】:2012-10-15 08:53:31
【问题描述】:


长话短说:Tkinter 中是否有获取小部件主框架名称的功能?

让我再告诉你一点:
有一个Button,名为“BackButton”

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

当我点击这个按钮时,有一个名为“CloseFrame”的函数,它关闭当前的框架(并做一些其他的事情),在本例中是“SCPIFrame”。但是为此,我需要 Frame 的名称,其中存在 BackButton。 有任何想法吗?感谢您的帮助。

【问题讨论】:

    标签: widget tkinter frame master


    【解决方案1】:

    我认为最好的方法是使用 .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 ;) 
    

    【讨论】:

      【解决方案2】:

      从字面上回答你的问题:

      是否有获取小部件主框架名称的功能 Tkinter?

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

      parent_name = widget.winfo_parent()
      parent = widget._nametowidget(parent_name)
      

      【讨论】:

      • 当我尝试打印 BackButton 的父名称时,我得到一个数字:.33500616。 self.parent_name = self.BackButton.winfo_parent()print self.parent_name
      • 这个数字是 Tcl 变量名。 _nametowidget 检索相应的 Tkinter 实例。谈论对象的 the 名称有点可疑,因为可以将许多变量绑定到该对象。然而,我们处于 Tcl 之上的 Tkinter 间接提供一个唯一的 name 作为 Tcl 变量名的情况。
      【解决方案3】:

      如果您使用面向对象的编程风格,主框架要么是对象本身,要么是对象的属性。例如:

      class MyApplication(tk.Tk):
          ...
          def close_frame(self):
              # 'self' refers to the root window
      

      以非 OO 方式解决此问题的另一种简单方法是将 master 存储在全局窗口中(对于非常小的程序可以正常工作,但不推荐用于任何需要随时间维护的程序),或者您可以将其传递给回调。例如:

      self.BackButton = Button(..., command=lambda root=self.SCPIFrame: self.close_frame(root))
      ...
      def CloseFrame(self, root):
          # 'root' refers to whatever window was passed in
      

      【讨论】:

        猜你喜欢
        • 2012-02-04
        • 1970-01-01
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 1970-01-01
        • 2011-12-13
        • 2013-08-13
        • 1970-01-01
        相关资源
        最近更新 更多