不同类中的Python3 Tkinter Checkbutton意外联动问题
问题现象
创建多个Frame1实例后,点击任意实例中的Checkbutton,所有实例里对应位置的Checkbutton会同时被激活。运行以下代码可复现:
from tkinter import * class Frame1(Frame): def __init__(self, parent): Frame.__init__(self, parent, bg="lightgray") self.parent = parent self.texto=[None]*10 self.cboton=[None]*10 self.widgets() def widgets(self): for row1 in range(10): t="V%s"%row1 self.cboton[row1]=Checkbutton(self, padx=7, relief=RIDGE, text=t, onvalue=1, offvalue=0, font='Courier 10') self.cboton[row1].grid(row=row1, column=0) self.texto[row1] = Text(self,width=5, height=1) self.texto[row1].insert(INSERT, "00.00") self.texto[row1].grid(row=row1, column=1) class MainW(Tk): def __init__(self, parent): Tk.__init__(self, parent) self.parent = parent self.mainWidgets() def mainWidgets(self): self.window=[None]*18 for col in range(18): texto="Bloq-#%i"%col self.label = Label(self, text=texto) self.label.grid(row=0, column=col) self.window[col] = Frame1(self) self.window[col].grid(row=1, column=col) if __name__=="__main__": app = MainW(None) app.mainloop()
预期:每个类实例的变量应独立,不同实例的Checkbutton不会互相影响。
问题原因
Tkinter的Checkbutton如果未显式指定variable参数,会默认使用同一个全局内部变量。所有未绑定独立变量的Checkbutton都会共享这个变量,导致状态联动。
解决方案
给每个Checkbutton绑定独立的IntVar变量,确保每个实例的变量互不干扰。修改Frame1类如下:
class Frame1(Frame): def __init__(self, parent): Frame.__init__(self, parent, bg="lightgray") self.parent = parent self.texto=[None]*10 self.cboton=[None]*10 # 为每个Checkbutton创建独立的状态变量 self.var = [IntVar() for _ in range(10)] self.widgets() def widgets(self): for row1 in range(10): t="V%s"%row1 self.cboton[row1]=Checkbutton(self, padx=7, relief=RIDGE, text=t, # 绑定独立的状态变量 variable=self.var[row1], onvalue=1, offvalue=0, font='Courier 10') self.cboton[row1].grid(row=row1, column=0) self.texto[row1] = Text(self,width=5, height=1) self.texto[row1].insert(INSERT, "00.00") self.texto[row1].grid(row=row1, column=1)
修改后,每个Frame1实例的Checkbutton都拥有独立的状态变量,点击其中一个不会影响其他实例的按钮状态。
内容的提问来源于stack exchange,提问作者mathengineer
相关产品推荐
相关产品推荐

