Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 views
in Technique[技术] by (71.8m points)

python - Tkinter: Configure method for labels dynamically generated

I am trying to change the labels of my application with the configure method. The Labels are dynamically made in a for loop. Here is part of the code:

# create a list of reference for labels equal to zero
self.lbl_areas = []
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))

# Place labels on the application using grid             
for i,v in enumerate(self.lbl_areas):
    v.grid(row=2+i,column=1,sticky=tk.W)

# Try to change the value
for i in range(0, len(self.samples)):
    self.lbl_areas[i].configure(textvariable=lbl_val[i]) # other values

The default zero values are displayed but the configure method seems not to work. What do I do wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...