There are two ways to update a label after it's been created. The first is to use a textvariable, where you update the variable and the label automatically picks up the change. The second is where you don't use a textvariable, and instead just change the label's text. You're trying to mix the two.
In my opinion, the best way is to not use a textvariable. It's an extra object you need to keep track of which provides no extra benefit (in this case, anyway).
In your case I would write the code like this:
for i in range(0, len(self.samples)): # number of labels
self.lbl_areas.append(tk.Label(self.win,text="0"))
...
for i in range(0, len(self.samples)):
self.lbl_areas[i].configure(text=lbl_val[i])
If you want to use the textvariable
attribute, then you need to save a reference to the variable so that you can set it later:
for i in range(0, len(self.samples)): # number of labels
lbl=tk.IntVar()
lbl.set(0)
self.lbl_areas.append(tk.Label(self.win,textvariable=lbl))
self.lbl_vars.append(lbl)
...
for i in range(0, len(self.samples)):
self.lbl_vars[i].set(lbl_val[i])
Notice that in both cases, you must call a function (configure
or set
) to change the value. You either call it on the widget (widget.configure(...)
) or on the variable (var.set(...)
). Unless you're taking advantage of the special properties of a tkinter variable -- such as sharing the variable between two or more widgets, or using variable traces -- your code will be less complicated without the textvariable
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…