使用类创建Tkinter Notebook多标签失败:仅显示最后一个标签
解决Tkinter Notebook多标签仅显示最后一个的问题
你遇到的问题核心是类属性被所有实例共享,导致多个标签其实复用了同一个Frame,最终只显示最后创建的那个标签。
问题根源
在Tabs类里,current_tab、current_from、current_to、result这些变量是直接定义在类下的类属性,所有Tabs实例会共用同一个这些变量。当你创建第二个标签时,其实是把同一个current_tab重新添加到notebook里,覆盖了之前的设置,所以界面只显示最后一个标签。
修正方案
把这些类属性改成实例属性,在__init__方法里初始化每个实例独有的变量:
from tkinter import * from tkinter import ttk class Tabs: # 移除类属性定义,移到__init__里 def __init__(self, name: str, units, calc_mode: str): self.name = name self.units = units self.calc_mode = calc_mode # 每个实例创建自己的Frame和变量 self.current_tab = Frame(notebook) self.current_entry = None self.current_from = StringVar() self.current_to = StringVar() self.result = StringVar() def create_frame(self): notebook.add(self.current_tab, text=self.name) Label(self.current_tab, text=self.name, font=("Arial", 30, "bold"), pady=20, padx=60).grid(row=0, column=1, columnspan=3) Label(self.current_tab, text="From: ", font=("Arial", 18, "bold")).grid(row=1, column=0) self.current_entry = Entry(self.current_tab, font="arial") self.current_entry.grid(row=1, column=2) self.current_from.set("Select") OptionMenu(self.current_tab,self.current_from,*self.units.keys()).grid(row=1, column=3) Label(self.current_tab, text="To: ", font=("Arial", 18, "bold")).grid(row=2, column=0) self.current_to.set("Select") OptionMenu(self.current_tab, self.current_to, *self.units.keys()).grid(row=2, column=2) Label(self.current_tab, text="Result: ", font=("Arial", 18, "bold", "italic"), width=10).grid(row=4,column=0) self.result.set("") print_result = Label(self.current_tab, textvariable=self.result, font=("Arial", 28, "bold")) print_result.grid(row=4, column=2) Button(self.current_tab, text="Calculate", font=("Arial", 18, "italic"), pady=4, command=self.calculate).grid(row=3,column=2) # 补充calculate方法避免点击按钮报错 def calculate(self): # 在这里编写你的计算逻辑 pass
创建标签的代码保持不变,同时补充完整的窗口初始化代码:
# 定义单位字典示例 temp_units = {"Celsius": "C", "Fahrenheit": "F", "Kelvin": "K"} length_units = {"Meter": "m", "Foot": "ft", "Inch": "in"} # 窗口初始化 root = Tk() notebook = ttk.Notebook(root) notebook.pack(fill=BOTH, expand=True) # 创建标签 tempertaure_tab = Tabs("Temperature", temp_units, "temperature") tempertaure_tab.create_frame() length_tab = Tabs("Length", length_units, "normal") length_tab.create_frame() root.mainloop()
关键修改点
- 把原来的类属性全部移到
__init__方法中,用self.前缀定义,确保每个Tabs实例都有自己独立的Frame和变量 - 补充了
calculate方法的空实现,避免点击按钮时触发报错
这样修改后,每个标签都会创建自己独立的Frame,就能正常显示多个标签了。
内容的提问来源于stack exchange,提问作者lorinctekker
相关产品推荐
相关产品推荐

