如何获取tab_id以将其设置为活动标签

时间:2020-07-19 09:40:03

标签: python tkinter tkinter-layout

我正在尝试使用tkinter构建文本编辑器。我只是想将焦点设置在新打开的tab.by中,可以使用静态tab_id进行即时设置,但是如果我一次具有15个以上的选项卡,则很难找到tab_id。我想要带有tab_name或tab_title或其他任何方式的tab_id
这是我的代码

import tkinter as tk
from tkinter import ttk, filedialog
import os

root = tk.Tk()
root.title("Tab Widget")
tabControl = ttk.Notebook(root)


def open_file(event=None):
    file1 = filedialog.askopenfile(mode='r', initialdir=os.getcwd(), filetypes=(('All files', '*.*'), ('Text files', '*.txt'))).name
    with open(file1) as f:
        content_in_file = f.read()
        new_tab = TabWin(tabControl, f'{file1.rsplit("/", 1)[-1]}').create_tab()
    new_tab.delete(1.0, tk.END)
    new_tab.insert(1.0, content_in_file)

class TabWin:
    def __init__(self, parent, title, text=None, file_path=None):
        self.parent = parent
        self.tab_title = title
        self.text = text
        self.tab_id = title
        self.tab = tk.Text(parent)

    def create_tab(self):
        self.parent.add(self.tab, text=self.tab_title)
        return self.tab

tab3 = TabWin(tabControl, 'pavan').create_tab()
tabControl.pack(expand=1, fill="both")
root.bind('<Control o>', open_file)
root.mainloop()

1 个答案:

答案 0 :(得分:2)

您可以通过Notebook的内置函数来完成此操作,例如:

import tkinter as tk
from tkinter import ttk, filedialog
import os

root = tk.Tk()
root.title("Tab Widget")
tabControl = ttk.Notebook(root)


def open_file(event=None):
    file1 = filedialog.askopenfile(mode='r', initialdir=os.getcwd(), filetypes=(('All files', '*.*'), ('Text files', '*.txt'))).name
    with open(file1) as f:
        content_in_file = f.read()
        new_tab = TabWin(tabControl, f'{file1.rsplit("/", 1)[-1]}').create_tab()
    new_tab.delete(1.0, tk.END)
    new_tab.insert(1.0, content_in_file)
    tabControl.select(new_tab)

class TabWin:
    def __init__(self, parent, title, text=None, file_path=None):
        self.parent = parent
        self.tab_title = title
        self.text = text
        self.tab_id = title
        self.tab = tk.Text(parent)

    def create_tab(self):
        self.parent.add(self.tab, text=self.tab_title)
        return self.tab

tab3 = TabWin(tabControl, 'pavan').create_tab()
tabControl.pack(expand=1, fill="both")
root.bind('<Control o>', open_file)
root.mainloop()

,请注意,根据docs,已经有一个内置函数来跟踪您的标签页。您只需在tabControl.select(new_tab) new_tab的行中替换为二进制数,那么第一个默认值将是0,下一个默认值将是1,依此类推。

如果出于任何原因想要以其他方式跟踪,则可以每次将new_tab存储在列表或字典中。让我知道你是否在这里错过什么。

相关问题