| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- import tkinter as tk
- from tkinter import ttk
- def show_tab(index):
- notebook.select(index) # 使用 notebook 的 select 方法切换到指定索引的 tab
- root = tk.Tk()
- root.title("自定义按钮切换 Notebook 内容")
- # 创建一个 Style 实例
- style = ttk.Style()
- # 为我们的 Notebook 创建一个新的样式名称
- notebook_style_name = "NoTabs.TNotebook"
- style.configure(notebook_style_name) # 可以进行其他配置,如果需要
- # 移除这个新样式的 Tab 布局
- style.layout(notebook_style_name + ".Tab", [])
- notebook = ttk.Notebook(root, style=notebook_style_name) # 将自定义样式应用到这个 Notebook
- notebook.pack(fill="both", expand=True)
- # 创建不同的内容 Frame
- tab1_content = ttk.Frame(notebook)
- label1 = tk.Label(tab1_content, text="这是选项卡 1 的内容", padx=50, pady=50)
- label1.pack(expand=True, fill="both")
- notebook.add(tab1_content, text="标签一") # 虽然设置了 text,但我们会隐藏标签
- tab2_content = ttk.Frame(notebook)
- label2 = tk.Label(tab2_content, text="这是选项卡 2 的内容", padx=50, pady=50)
- label2.pack(expand=True, fill="both")
- notebook.add(tab2_content, text="标签二") # 同样设置了 text
- tab3_content = ttk.Frame(notebook)
- label3 = tk.Label(tab3_content, text="这是选项卡 3 的内容", padx=50, pady=50)
- label3.pack(expand=True, fill="both")
- notebook.add(tab3_content, text="标签三") # 同样设置了 text
- # 创建自定义按钮
- button1 = tk.Button(root, text="显示内容 1", command=lambda: show_tab(0))
- button1.pack(side="left", padx=5)
- button2 = tk.Button(root, text="显示内容 2", command=lambda: show_tab(1))
- button2.pack(side="left", padx=5)
- button3 = tk.Button(root, text="显示内容 3", command=lambda: show_tab(2))
- button3.pack(side="left", padx=5)
- root.mainloop()
- # import tkinter as tk
- # from tkinter import ttk
- #
- # def add_new_tab():
- # global tab_count
- # tab_count += 1
- # new_tab = ttk.Frame(notebook)
- # label = tk.Label(new_tab, text=f"这是动态添加的选项卡 {tab_count}", padx=50, pady=50)
- # label.pack(expand=True, fill="both")
- # notebook.add(new_tab, text=f"动态标签 {tab_count}")
- #
- # root = tk.Tk()
- # root.title("动态添加 Notebook 标签")
- #
- # notebook = ttk.Notebook(root)
- # notebook.pack(fill="both", expand=True)
- #
- # # 初始添加一些标签
- # tab1 = ttk.Frame(notebook)
- # label1 = tk.Label(tab1, text="初始选项卡 1", padx=50, pady=50)
- # label1.pack(expand=True, fill="both")
- # notebook.add(tab1, text="标签一")
- #
- # tab2 = ttk.Frame(notebook)
- # label2 = tk.Label(tab2, text="初始选项卡 2", padx=50, pady=50)
- # label2.pack(expand=True, fill="both")
- # notebook.add(tab2, text="标签二")
- #
- # tab_count = 2 # 记录已经添加的标签数量
- #
- # # 添加一个按钮,点击时动态添加新标签
- # add_button = tk.Button(root, text="添加新标签", command=add_new_tab)
- # add_button.pack(pady=10)
- #
- # root.mainloop()
|