Reputation: 19
I want to build a user interface like this:
the code is:
for ii in range(len(solutions)):
tk.Label(text=solutions[ii], bg="lightsalmon", fg="black", font=("times", 10), relief=tk.RIDGE, width=50, anchor="w").grid(row=ii+1,column=3, ipadx=0, ipady=0, rowspan=1, sticky=tk.N+tk.E+tk.S+tk.W)
v = StringVar()
checkbutton1 = Checkbutton(mywindow, text='YES', onvalue='YES', variable=v, bg="red", fg="black", font=("times", 10), width=3, anchor="w", command=close_yes)
checkbutton1.deselect()
checkbutton1.grid(row=ii+1, column=4, ipadx=0, ipady=0, rowspan=1, sticky=tk.N+tk.E+tk.S+tk.W)
checkbutton2 = Checkbutton(mywindow, text='NO', onvalue='NO', variable=v, bg="red", fg="black", font=("times", 10), width=3, anchor="w", command=close_no)
checkbutton2.deselect()
checkbutton2.grid(row=ii+1, column=5, ipadx=0, ipady=0, rowspan=1, sticky=tk.N+tk.E+tk.S+tk.W)
the problem is I can only get the last checkbutton's value, can you help me to fix this problem? thank you very much!
Upvotes: 0
Views: 203
Reputation: 47219
You need to use a list to holds the StringVar
instances. To access the correct instance of StringVar
inside close_yes()
and close_no()
functions, you need to pass the correct index to them using lambda and default value of lambda argument:
def close_yes(i):
print('close_yes:', i, v[i].get())
def close_no(i):
print('close_no:', i, v[i].get())
...
v = [None] * len(solutions) # list to hold the StringVar instances
for ii in range(len(solutions)):
tk.Label(text=solutions[ii], bg="lightsalmon", fg="black", font=("times", 10), relief=tk.RIDGE,
width=50, anchor="w").grid(row=ii+1,column=3, ipadx=0, ipady=0, rowspan=1, sticky=tk.N+tk.E+tk.S+tk.W)
v[ii] = tk.StringVar()
checkbutton1 = tk.Checkbutton(mywindow, text='YES', onvalue='YES', variable=v[ii],
bg="red", fg="black", font=("times", 10), width=3, anchor="w",
command=lambda i=ii: close_yes(i)) # use lambda to pass the correct index to callback
checkbutton1.deselect()
checkbutton1.grid(row=ii+1, column=4, ipadx=0, ipady=0, rowspan=1, sticky=tk.N+tk.E+tk.S+tk.W)
checkbutton2 = tk.Checkbutton(mywindow, text='NO', onvalue='NO', variable=v[ii],
bg="red", fg="black", font=("times", 10), width=3, anchor="w",
command=lambda i=ii: close_no(i))
checkbutton2.deselect()
checkbutton2.grid(row=ii+1, column=5, ipadx=0, ipady=0, rowspan=1, sticky=tk.N+tk.E+tk.S+tk.W)
Upvotes: 2