如何从 ttk.Notebook 选项卡获取小部件对象? [英] How to get widget object from ttk.Notebook tab?

查看:41
本文介绍了如何从 ttk.Notebook 选项卡获取小部件对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 ttk.Notebook 类的笔记本小部件.在这个笔记本中,我添加了许多标签:

I have notebook widget of class ttk.Notebook. In this notebook I'm adding many tabs:

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

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

How can I get tab object and not tab name?

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

So, there is children dictionary. OK that brings next problem.

我真正想做的是将我的手放在 Notebook 中活动选项卡的对象上.所以我有这个:

What I really want to do is to take my hands on object of active tab in Notebook. So I have this:

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

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

but it looks ugly. Unfortunately widget name returned by select() has not exactly same format as widget names in children[]. Is there any method of reliable translation of one format to another or split() will never fail in this situation?

这是问题的演示:

#!/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()

推荐答案

notebook.tabs() 调用返回标签名称"列表对应于子部件对象.对 someWidget.nametowidget(tab_name) 的调用解析为与该选项卡关联的子小部件.

The notebook.tabs() call returns a list of "tab names" which correspond to the children widget objects. A call to someWidget.nametowidget(tab_name) resolves to the child widget associated with that tab.

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

In other words, the Notebook .tabs() method returns a list of the names of the Notebook's children.

对于您的更新:

同上,只是现在是:

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

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

Different versions of Python use different naming conventions, so using nametowidget() is the better way to go rather than manually processing the name to get the desired key to use for a reference into the children dict.

这篇关于如何从 ttk.Notebook 选项卡获取小部件对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆