I am trying to generate standalone Checkbuttons in loop but who has the same name Checkbutton works together. I don’t know where is my mistake…
#!/usr/bin/env python
#-*-coding:utf-8-*-
import os
from Tkinter import *
import ttk
def checkBoxText(st):
if st == 0:
st="Disabled"
if st == 1:
st="Enabled"
return st
root = Tk()
winSt={1:1,2:1,3:0,4:0}
cbTexts={}
cbVariables={}
cb={}
cb_x={ "1":"0.0", "2":"0.0", "3":"0.6", "4":"0.6" }
cb_y={"1": "0.1", "2": "0.8", "3": "0.1", "4": "0.8"}
for i in sorted(winSt.keys()):
cbTexts[i] = StringVar()
cbTexts[i].set(checkBoxText(winSt[i]))
cbVariables[i] = IntVar()
cbVariables[i].set(winSt[i])
cb[i] = Checkbutton(root, text=cbTexts[i].get(), variable=cbVariables[i].get())
cb[i].place(relx=cb_x[str(i)], rely=cb_y[str(i)], relheight=0.1,relwidth=0.4)
mainloop()
4
The problem is in this line:
cb[i] = Checkbutton(..., variable=cbVariables[i].get())
When you use the variable
attribute, you must give it a reference to a variable object, not the value contained in the object. Change the code to this:
cb[i] = Checkbutton(..., variable=cbVariables[i])
You’re making a somewhat similar mistake with the checkbutton text. You are creating a StringVar, but then using the value of the StringVar for the checkbutton text instead of the actual variable. Syntactically that’s correct when used with the text
attribute, but it’s doing more work than it needs to. You should either use the textvariable
attribute, or simply not create a StringVar.
Here’s how to use the textvariable
attribute instead of the text
attribute:
cb[i] = Checkbutton(root, textvariable=cbTexts[i], ...)
You don’t need the StringVar at all if this text will never change. If that’s the case, you can just do this and save a couple lines of code:
cb[i] = Checkbutton(root, text=checkBoxText(winSt[i]), ...)