【问题标题】:How to get widget object from ttk.Notebook tab?如何从 ttk.Notebook 选项卡获取小部件对象?
【发布时间】:2017-02-02 20:00:15
【问题描述】:

我有 ttk.Notebook 类的笔记本小部件。在此笔记本中,我添加了许多选项卡:

notebook.add(child=my_object, text='my tab')

如何获取选项卡对象而不是选项卡名称?

更新 1

所以,有儿童词典。好的,这带来了下一个问题。

我真正想做的是亲手接触笔记本中活动选项卡的对象。所以我有这个:

notebook.children[notebook.select().split('.')[2]])

但它看起来很丑。不幸的是,select() 返回的小部件名称与 children[] 中的小部件名称格式不完全相同。是否有任何方法可以可靠地将一种格式转换为另一种格式,或者 split() 在这种情况下永远不会失败?

这是问题的演示:

#!/usr/bin/env python3

from tkinter import *
from tkinter.ttk import *


class App(Tk):
    def __init__(self):
        super().__init__()
        notebook = Notebook(self)
        notebook.add(child=Frame(notebook), text='tab1')
        notebook.add(child=Frame(notebook), text='tab2')
        notebook.add(child=Frame(notebook), text='tab3')
        notebook.pack()

        print('Tabs are: ', notebook.children.keys())
        print('Active tab: ', notebook.select())
        print(type(notebook.children[notebook.select().split('.')[2]]))

App().mainloop()

【问题讨论】:

  • my_object 赋值给变量并使用这个变量。

标签: python tkinter tk


【解决方案1】:

notebook.tabs() 调用返回与子窗口小部件对象对应的“选项卡名称”列表。对someWidget.nametowidget(tab_name) 的调用将解析为与该选项卡关联的子小部件。

换句话说,Notebook .tabs() 方法返回 Notebook 子项名称的列表。

对于您的更新:

与上述相同,只是现在是:

active_object = notebook.nametowidget(notebook.select())

不同版本的 Python 使用不同的命名约定,因此使用 nametowidget() 是更好的方法,而不是手动处理名称以获取所需的键以用于对子 dict 的引用。

【讨论】:

    【解决方案2】:

    ttk.Notebook 将 Tab-Objects 存储在它的 children 属性中,这是一个 python 字典,例如:

    {my_tab._name: tab_object} e.g. {'4465111168': <Viewer.Tab object .4435079856.4465020320.4465111168>}
    

    您可以通过以下方式访问选项卡对象:

    my_notebook.children[my_tab._name]
    

    其中 my_notebook 是 ttk.Notebook 对象的实例,而 my_tab 是您的 Tab 对象。选项卡属性_name 是作为键存储在my_notebook.children 中的值。

    因此,访问选项卡对象的最简单方法是将您的 my_tab._name 值单独存储在列表或变量中。 存储所有名称后,您可以像上面一样访问子字典。

    更多参考请见https://docs.python.org/3.1/library/tkinter.ttk.html

    【讨论】:

      【解决方案3】:

      删除了我之前的帖子,因为基本上都是bs。

      要获取实际的小部件对象,请使用以下代码:

      name =  mywidget.winfo_name() # this returns this ominous string
                                    # of numbers and dots
      
      object_from_name = mywidget._nametowidget(name) # this returns your
                                                      # actual widget
      

      如果您打印 object_from_name,您很可能会得到该名称。但我认为,这就是 tkinter 小部件对象的表示方式。 你应该可以做到

      object_from_name.config(text="stuff", do_further_stuff_here="")
      

      【讨论】:

      • 小部件名称 (.234567890.1234567.123456689.354567) 似乎是从根对象开始的完整树。
      【解决方案4】:

      这就是我的诀窍:

      for name in notebook.tabs():
          tab_widget = notebook.nametowidget(name)
      

      【讨论】:

        猜你喜欢
        • 2014-01-16
        • 1970-01-01
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 2011-09-04
        • 2020-08-13
        • 1970-01-01
        • 2011-05-25
        相关资源
        最近更新 更多