You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为tkinter.ttk.Notebook标签页添加关闭与新增按钮?

实现带新增和关闭按钮的ttk.Notebook标签页

要同时实现点击加号新增标签、点击关闭按钮移除对应标签的功能,核心是把两个逻辑整合到ttk.Notebook的事件和布局管理中,以下是完整可运行的实现方案:

import tkinter as tk
from tkinter import ttk

class TabbedApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("带新增/关闭的标签页")
        self.geometry("600x400")

        self.notebook = ttk.Notebook(self)
        self.notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 初始化加号标签
        self.add_plus_tab()

        # 绑定标签切换事件
        self.notebook.bind("<<NotebookTabChanged>>", self.on_tab_switch)

    def add_plus_tab(self):
        # 创建加号标签的占位容器
        plus_frame = ttk.Frame(self.notebook)
        self.notebook.add(plus_frame, text="+")

    def on_tab_switch(self, event):
        current_idx = self.notebook.index(self.notebook.select())
        # 判断是否点击了最后一个加号标签
        if current_idx == self.notebook.index("end") - 1:
            self.create_new_tab()

    def create_new_tab(self):
        # 创建新标签的内容容器
        new_tab_frame = ttk.Frame(self.notebook)
        tab_title = f"标签 {self.notebook.index('end')}"

        # 构建带关闭按钮的标签标题区域
        tab_header = ttk.Frame(self.notebook)
        ttk.Label(tab_header, text=tab_title).pack(side=tk.LEFT, padx=2)
        close_btn = ttk.Button(tab_header, text="×", width=2, command=lambda: self.remove_tab(new_tab_frame))
        close_btn.pack(side=tk.RIGHT, padx=2)

        # 添加新标签并替换标题为自定义布局
        self.notebook.add(new_tab_frame)
        active_tab_id = self.notebook.select()
        self.notebook.tab(active_tab_id, window=tab_header)

        # 重新调整加号标签到最后
        self.notebook.forget(self.notebook.index("end") - 1)
        self.add_plus_tab()

    def remove_tab(self, target_frame):
        # 获取目标标签的索引并移除
        tab_idx = self.notebook.index(target_frame)
        self.notebook.forget(tab_idx)

        # 确保始终保留加号标签
        if self.notebook.index("end") == 0:
            self.add_plus_tab()

if __name__ == "__main__":
    app = TabbedApp()
    app.mainloop()

关键逻辑说明

  • 加号标签的持久化:始终在Notebook的末尾保留一个加号标签,用户点击它时触发新标签创建,创建完成后重新将加号标签移到最后,保证它始终是最后一个选项。
  • 自定义标签标题:通过notebook.tab(tab_id, window=tab_header)将默认的文本标签替换成包含标题文本和关闭按钮的Frame,实现每个标签带独立关闭按钮的效果。
  • 事件触发机制:利用ttk.Notebook内置的<<NotebookTabChanged>>事件检测用户的标签切换操作,判断是否触发新增逻辑。
  • 关闭后的状态维护:移除标签后检查剩余标签数量,如果所有普通标签都被关闭,自动重新添加加号标签,避免界面空无标签的情况。

内容的提问来源于stack exchange,提问作者dragonkyl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:05:05