问题
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?
UPDATE 1
So, there is children dictionary. OK that brings next problem.
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]])
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?
This is demo of problem:
#!/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()
回答1:
ttk.Notebook stores Tab-Objects within it's children attribute which is a python dictionary like:
{my_tab._name: tab_object} e.g. {'4465111168': <Viewer.Tab object .4435079856.4465020320.4465111168>}
You can access a Tab-object via:
my_notebook.children[my_tab._name]
Where my_notebook is an instance of an ttk.Notebook object and my_tab is your Tab object. The tab attribute _name
is the value wich get's stored as the key in my_notebook.children
.
So the easiest way of accessing the tab objects would be by separately storing your my_tab._name
values in a list or variable.
With all the names stored you can access the children dict like above.
See https://docs.python.org/3.1/library/tkinter.ttk.html for more reference.
回答2:
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.
In other words, the Notebook .tabs()
method returns a list of the names of the Notebook's children.
回答3:
Deleted my former post, because it was basically bs.
To get the actual widget-object use the following code:
name = mywidget.winfo_name() # this returns this ominous string
# of numbers and dots
object_from_name = mywidget._nametowidget(name) # this returns your
# actual widget
If you print object_from_name you'll likely get the name. But I think, this is how tkinter widget objects are represented. You should be able to do
object_from_name.config(text="stuff", do_further_stuff_here="")
来源:https://stackoverflow.com/questions/42011264/how-to-get-widget-object-from-ttk-notebook-tab