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

Tkinter Notebook问题:实现点击按钮新增标签而非替换原有标签

问题原因

你每次点击按钮都会重新创建一个ttk.Notebook实例并将其pack到main_frame中,这会导致新的Notebook覆盖掉之前的实例,视觉上表现为原有标签被替换。要实现标签共存,核心是只创建一次Notebook实例,后续操作仅针对这个实例进行标签的显示或切换。

修正后的代码(切换已有标签)
from tkinter import *
from tkinter import ttk

root = Tk()

root.title('Switch Pages')
root.geometry('500x500')
root.minsize(400, 400)

# 按钮栏Frame
button_frame = Frame(root, height=50, bg='red')
button_frame.pack(side=BOTTOM, fill=BOTH)

# 主内容Frame
main_frame = Frame(root, bg='yellow')
main_frame.pack(expand=True, fill=BOTH)

# 仅创建一次Notebook实例,添加所有需要的标签页
notebook = ttk.Notebook(main_frame)
tab1 = Frame(notebook)
tab2 = Frame(notebook)
notebook.add(tab1, text='Snooker Table 1')
notebook.add(tab2, text='Snooker Table 2')
notebook.pack(expand=True, fill=BOTH)

# 可选:默认隐藏所有标签,点击按钮后再显示
# notebook.hide(tab1)
# notebook.hide(tab2)

def select_tab(no):
    # 根据索引切换到对应标签,自动显示
    notebook.select(no)

button1 = Button(button_frame, text="Button 1", command=lambda: select_tab(0))
button1.grid(row=0, column=5)
button2 = Button(button_frame, text="Button 2", command=lambda: select_tab(1))
button2.grid(row=0, column=6)

root.mainloop()
关键修改点
  • 将ttk.Notebook的创建、标签页添加逻辑移到函数外部,确保整个应用生命周期内只有一个Notebook实例。
  • 简化按钮绑定的函数,仅负责根据索引切换/显示对应标签,避免重复创建组件。

扩展:点击按钮新增标签页(标签共存)

如果你的需求是每次点击按钮都新增一个独立标签页,而非切换已有标签,可以使用以下代码:

from tkinter import *
from tkinter import ttk

root = Tk()

root.title('Add Tabs')
root.geometry('500x500')
root.minsize(400, 400)

button_frame = Frame(root, height=50, bg='red')
button_frame.pack(side=BOTTOM, fill=BOTH)

main_frame = Frame(root, bg='yellow')
main_frame.pack(expand=True, fill=BOTH)

notebook = ttk.Notebook(main_frame)
notebook.pack(expand=True, fill=BOTH)

# 记录标签序号,避免重复命名
tab_index = 0

def add_new_tab(base_name):
    global tab_index
    tab_index += 1
    # 创建新标签页并添加到Notebook
    new_tab = Frame(notebook)
    notebook.add(new_tab, text=f'{base_name} {tab_index}')
    # 自动切换到新创建的标签
    notebook.select(new_tab)

button1 = Button(button_frame, text="Add Table", command=lambda: add_new_tab('Snooker Table'))
button1.grid(row=0, column=5)
button2 = Button(button_frame, text="Add Pool Table", command=lambda: add_new_tab('Pool Table'))
button2.grid(row=0, column=6)

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:13:10