【问题标题】:how to get tab_id to set it as active tab如何获取 tab_id 将其设置为活动选项卡
【发布时间】:2020-07-19 09:40:03
【问题描述】:

我正在尝试使用 tkinter 构建一个文本编辑器。我只是想在新打开的选项卡中设置焦点。通过使用静态 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()

【问题讨论】:

    标签: python tkinter tkinter-layout


    【解决方案1】:

    您可以通过 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 存储在列表或字典中。如果您在这里遗漏了什么,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2013-07-24
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多