0

我想建立一个这样的用户界面:

代码是:

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)

问题是我只能得到最后一个检查按钮的值,你能帮我解决这个问题吗?非常感谢!

4

1 回答 1

2

您需要使用列表来保存StringVar实例。StringVar要访问正确的内部close_yes()和函数实例close_no(),您需要使用 lambda 和 lambda 参数的默认值将正确的索引传递给它们:

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)
于 2020-03-16T07:26:27.420 回答