【发布时间】:2021-10-11 22:45:29
【问题描述】:
我陷入了以下问题。使用 for 循环,我想制作一些复选框,这些复选框会自动更新一个标签,说明该复选框是否被勾选。但是,它给出了错误的结果(它总是说复选框被选中,无论是否如此;值得注意的是复选框默认未选中),see here how the GUI looks like (including error)。与复选框对应的 IntVar 工作正常,当勾选至少一个复选框并按下功能是读取复选框的按钮时可以看出。另见以下代码:
import tkinter as tk
top = tk.Tk()
n_passes = 3
checkbox_var = [0] * n_passes
checkbox = [0] * n_passes
def tick_passes(i): # update label saying if checkboxes are ticked
if checkbox_var[i].get == 0:
label = tk.Label(top, text = f"pass #{i} not ticked")
else:
label = tk.Label(top, text = f"pass #{i} ticked")
label.grid(row = 1, column = i)
def check_checkbox_var(): # check whether checkbox_var[i] is updated
for i in range(n_passes):
print(f"checkbox_var[i].get() = {checkbox_var[i].get()}")
for i in range(n_passes):
checkbox_var[i] = tk.IntVar() # turn on/off certain passes
print(f"checkbox_var[i].get() = {checkbox_var[i].get()}")
checkbox[i] = tk.Checkbutton(top, text = f"Tick pass {i}", variable =
checkbox_var[i], command = tick_passes(i))
checkbox[i].grid(row = 0, column = i, sticky=tk.W)
var_button = tk.Button(top, text = "Check checkbox_var", command =
check_checkbox_var).grid(row = 2, column = 0) # check whether checkbox_var[i] is updated
top.mainloop()
有人可以帮我更新标签吗?如果有其他方法可以解决此问题,例如使用要按下的按钮而不是要勾选的检查按钮,这也适用于我。
【问题讨论】:
-
if checkbox_var[i].get == 0:应该是if checkbox_var[i].get() == 0:,command = tick_passes(i)应该是command=lambda i=i:tick_passes(i) -
将按钮的语句移出上一个循环;先创建标签,然后在
tick_passes中更新它 -
非常感谢@JasonYang!你帮了我很多
标签: python for-loop tkinter checkbox