tkinter两列Checkbutton意外绑定联动问题求助
问题根因
你创建两个列的Checkbutton控件时,没有显式将控件和预先定义的IntVar变量绑定,Tkinter会为没有指定variable参数的Checkbutton自动分配默认内部变量,两个列按顺序生成的控件刚好匹配到了相同的默认变量,所以点击一个会同步触发另一个的状态变化。
修复方案
修改两处Checkbutton的创建代码,显式绑定对应的变量即可:
- 修改
cb_packer方法里的Checkbutton创建逻辑,添加variable参数
# 原代码 cb = tk.Checkbutton(self.left_frame, text=key, bg='white', command=lambda i=index: self.cb_changer(list(self.part_dict)[i])) # 修改后代码 cb = tk.Checkbutton(self.left_frame, text=key, bg='white', variable=self.part_dict[key]['variable_cb'], command=lambda i=index: self.cb_changer(list(self.part_dict)[i]))
- 修改
cb2_packer方法里的Checkbutton创建逻辑,同样添加variable参数
# 原代码 cb2 = tk.Checkbutton(self.right_frame, text=self.part_dict[key]['file'], bg='white', command=lambda i=index: self.cb2_changer(list(self.part_dict)[i])) # 修改后代码 cb2 = tk.Checkbutton(self.right_frame, text=self.part_dict[key]['file'], bg='white', variable=self.part_dict[key]['variable_cb2'], command=lambda i=index: self.cb2_changer(list(self.part_dict)[i]))
补充说明:如果你不需要在点击复选框时执行额外的打印逻辑,还可以直接去掉command参数,Checkbutton会自动同步绑定的IntVar值,不需要自己写cb_changer、cb2_changer方法手动修改变量值。
内容的提问来源于stack exchange,提问作者user498823
相关产品推荐
相关产品推荐

