[英]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.