【问题标题】:Tkinter Checkbutton questionsTkinter Checkbutton 问题
【发布时间】:2020-03-16 01:14:15
【问题描述】:

我要构建a user interface like this:

代码是:

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)

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

【问题讨论】:

  • 您可以使用列表来保存StringVar 实例。使用Radiobutton 而不是Checkbutton 更好吗?
  • 我试过了,还是不行
  • v = [None] * len(solutions) for ii in range(len(solutions)): v[ii] = StringVar() checkbutton1 = Checkbutton(mywindow, text='YES', onvalue ='YES', variable=v[ii], bg="red", fg="black", font=("times", 10), width=3, anchor="w", command=close_yes)跨度>
  • 无法粘贴完整的代码,因为太长了
  • 如何获取close_yes()close_no()函数中变量的值?

标签: python tkinter tkinter.checkbutton


【解决方案1】:

您需要使用一个列表来保存StringVar 实例。要在 close_yes()close_no() 函数中访问正确的 StringVar 实例,您需要使用 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)

【讨论】:

  • 天哪,解决了!非常感谢!我在这里呆了几天!
猜你喜欢
  • 2018-05-17
  • 2023-04-07
  • 2022-08-18
  • 1970-01-01
  • 2016-06-16
  • 2018-10-26
  • 1970-01-01
  • 2018-10-20
  • 2020-02-21
相关资源
最近更新 更多