Finding the currently selected tab of Ttk Notebook

前端 未结 5 1425
南旧
南旧 2021-02-07 19:58

I have a Ttk Notebook widget containing 8 Frames - so, 8 tabs. Each frame contains a Text widget. I have a button outside the Notebook widget, and I want to insert text into the

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 20:08

    There are two simple ways to see which tab is selected:

    nb.select()  # returns the Tab NAME (string) of the current selection
    

    and

    nb.index('current') # returns the Tab INDEX (number) of the current selection
    

    The .select() method can also be used to select which tab is currently active, via nb.select(tabId). Without the arg, it returns the tabId (in "name" form) of the current selection.

    The .index(tabId) converts a tabId into a numerical index. It also can take the string "end" which will return the number of tabs. So, nb.index(tkinter.END) is like a len() method for a notebook widget.

    When there are no tabs, .select() returns an empty string, but .index('current') throws an exception. So, if you want the index, I would say

    if nb.select():
        idx = nb.index('current')
    

    is the best way to go.

    In your particular case, you would probably want to grab the current notebook tab name and then convert that name into the actual child text widget, via the nametowidget() method, for manipulation. So...

    tabName = notebook.select()
    if tabName:
        textWidget = notebook.nametowidget(tabName) # here, 'notebook' could be any widget
        textWidget.insert(pos, text, tags)
    

    The nametowidget(name) method maps a Tkinter name to the actual widget. It is a method callable by any actual widget.

提交回复
热议问题