Using following code I try to get updated list of checkbuttons’ corresponding text values, everytime checkbutton is checked or unchecked:
import Tkinter as tk
opt = []
def chkbox_checked():
for ix, item in enumerate(cb):
opt.append(cb_v[ix].get())
print opt
root = tk.Tk()
mylist = [
'NR',
'ECEF X',
'ECEF Y',
'ECEF Z',
'height'
]
cb = []
cb_v = []
for ix, text in enumerate(mylist):
cb_v.append(tk.StringVar())
cb.append(tk.Checkbutton(root, text=text, onvalue=text, variable=cb_v[ix], comand=chkbox_checked))
cb[ix].grid(row=ix, column=0, sticky='w')
label = tk.Label(root, width=20)
label.grid(row=ix+1, column=0, sticky='w')
root.mainloop()
If for example all buttons are checked from the first to the last, my desired output would be:
['NR']
['NR','ECEF X]
['NR','ECEF X','ECEF Y']
['NR','ECEF X','ECEF Y','ECEF Z]
['NR','ECEF X','ECEF Y','ECEF Z','height',]
but with above code I get multiplied output and also there’s something wrong with checkbuttons themselves, their state is checked from the beginning.
Any help would be appreciated.
One problem with the above is the opt.append in chkbox_checked … Since this function gets called everytime a button is checked/unchecked, the length of the opt list will increase by the number of checkbuttons you have everytime one of the buttons is clicked. The solution (posted below) is to initialize opt when you create the buttons and then just update it’s elements in chkbox_checked. As far as the state of the buttons on creation, I’m not sure why they’re initially checked, but you can easily deselect the buttons at initialization as well using the deselect method.
Another trick that may be useful is instead of keeping 2 lists (cb and cb_v), you could just add the StringVars as attributes to your checkbuttons. e.g.:
Then you just have one list with all the data. The corresponding chkbox_checked would look like:
(Note this also eliminates the need for a global
optlist … although there are probably a whole bunch of other ways to get rid of that list)