Tkinter Query

Alex Martelli aleax at aleax.it
Thu Oct 10 04:04:22 EDT 2002


newt_e at blueyonder.co.uk wrote:

> Doh, sometimes it's so obvious it stares you in the face.
> 
> What I'm really trying to do is similar to
> 
>   lbls=[]
>   for i in [1,2,3,4,5]

You're missing a colon here, and you may as well use range(5).

>     lbl = Label(parent, text="Some Text")
>     lbls.append(lbl)
> 
>   lbls[3].configure(text="New Text")
> 
> Does lbls.append(lbl) only create a reference to lbl, 

Yes, or, to be even more picky and precise: it just adds one more
reference to the same object that variable lbl is also referring to
at this time.

But that's OK in this case, because in each leg of the loop you
create a new Label object and re-bind variable lbl to it -- so the
references you're adding to list lbls are all different, which
IS just what you want here.

> and would this make lbls[3].configure(text="New Text")
>  a nonsense? 

No, I think it does just what you mean it to do, in this case.

>  If so how do I get the actual value of lbl into the lbls
>  list?

If you're worried about the name lbl referring to the same
object as some item of list lbls, just avoid using that name,
for example by changing the whole loop into:

for i in range(5):
    lbls.append(Label(parent, text="Some Text"))

or equivalently:

lbls = [ Label(parent, text="Some Text") for i in range(5) ]

Although this is nicely idiomatic, there isn't any deep
problem with the equivalent snippet you posted, either.
Choose on stylistic grounds -- whatever you find clearest
and easiest to maintain in the future.

The last label object generated is referred to in two ways,
both as lbl and lbl[4] (remember indices go 0-up...) -- not
a biggie, and also fixable with a "del lbl" if you want (del
just removes ONE reference -- the object stays, because it
has another reference to it).


Alex




More information about the Python-list mailing list