繁体   English   中英

查找 Ttk Notebook 当前选中的选项卡

[英]Finding the currently selected tab of Ttk Notebook

我有一个包含 8 个框架的 Ttk Notebook 小部件 - 所以,8 个标签。 每个框架都包含一个文本小部件。 我在 Notebook 小部件外有一个按钮,我想在按下此按钮时将文本插入到当前选项卡文本小部件中。

这似乎需要确定当前选择了 Notebook 中的哪个小部件,但我似乎无法找到如何执行此操作。 我如何找到当前选择的选项卡?

或者,我怎样才能实现我想要的?

如果有帮助,这是我的笔记本的代码:

self.nb = Notebook(master)
self.nb.pack(fill='both', expand='yes', padx=10, pady=10)
self.frames = []
self.texts = []
for i in xrange(8):
  self.frames.append(Frame())
  self.nb.add(self.frames[i])
  self.texts.append(Text(self.frames[i]))
  self.texts[i].pack(fill='both')

您可以通过select方法检索选定的选项卡。 然而,这个方法返回一个 tab_id ,它没有多大用处。 index将其转换为所选选项卡的编号。

>>> nb.select()
'.4299842480.4300630784'
>>> nb.index(nb.select())
2

请注意,您还可以使用tab获取有关所选选项tab更多信息

>>> nb.tab(nb.select(), "text")
'mytab2'

您可以查看 Notebook 参考文档: http : //docs.python.org/3/library/tkinter.ttk.html#notebook

您可以使用"current"关键字获取当前选定的选项卡:

noteBook.index("current")

检查这个网站: https: //docs.python.org/2/library/ttk.html#tab-identifiers 24.2.5.3。 标签标识符

有两种简单的方法可以查看选择了哪个选项卡:

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

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

.select()方法也可用于通过nb.select(tabId)选择当前处于活动状态的选项卡。 如果没有 arg,它会返回当前选择的 tabId(以“名称”形式)。

.index(tabId)将 tabId 转换为数字索引。 它还可以采用字符串“end”,该字符串将返回选项卡的数量。 因此, nb.index(tkinter.END)就像笔记本小部件的len()方法。

当没有选项卡时, .select()返回一个空字符串,但.index('current')抛出异常。 所以,如果你想要索引,我会说

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

是最好的方法。

在您的特定情况下,您可能希望获取当前笔记本选项卡名称,然后通过nametowidget()方法将该名称转换为实际的子文本小部件以进行操作。 所以...

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

nametowidget(name)方法将 Tkinter 名称映射到实际小部件。 它是一种可由任何实际小部件调用的方法。

我根本不是专家,但希望我能帮助一些“新鲜的眼睛”。 我想这可能涉及到一些事情

def buttonclick():
      somevariablename = focus_get()
      #Print your text into the somevariable notebook could be
      #something like(not sure about the syntax):
      focusednotebook = somevariablename
      focusednotebook.insert('1.0', 'your text here')

yourbutton = Button(parent, text = "button name", command = buttonclick)
yourbutton.pack()

希望它有效或让你朝着正确的方向前进。

请随意编辑,因为我在这里很新,使用 python :-)

在 tk.Notebook 中获取目标标签很容易,您只需使用笔记本对象并定位当前标签的索引即可。 这可以按如下方式完成

 # creating a notebook object
 notebook = ttk.Notebook(root, height=height, width=width, padding=20)

 # Adding tabs
 notebook.add(bin_tab, text="Binary Conversion")
 notebook.add(oct_tab, text="Octal Conversion")
 notebook.add(hex_tab, text="Hexadecimal Conversion")

 print(notebook.index("current")) # returns 0, 1, 2depending on how many tabs you have in my case i have 3 which means index from 0 to 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM