[Tkinter] messed callbacks

Giacomo Boffi giacomo.boffi at polimi.it
Wed Sep 9 14:11:18 CEST 2009


"Diez B. Roggisch" <deets at nospam.web.de> writes:

> Giacomo Boffi wrote:
>
>> def doit(fr,lst):
>>   for c1,c2 in zip(lst[::2], lst[1::2]):
>>     subframe=Frame(fr)
>>     Label(subframe,text=c1+' <->
>>     '+c2).pack(side='left',expand=1,fill='both')
>>     Button(subframe,text='>',command=lambda: output(c1+'->'+c2)).pack()
>>     Button(subframe,text='<',command=lambda: output(c2+'->'+c1)).pack()
>>     subframe.pack(fill='x',expand=1)
>> 
>> why the messed callbacks? what's the right thing to do?
>
> Closures in python contain names, not the objects they refer to. So
> when you rebind that name (as you do above in your loop),

sorry, i'm not conscient of rebinding a name... what do you mean by
"rebind that name" exactly?

> the created callbacks will only refer to the last bound value of a
> name.
> 
> Create new closures, or bind arguments as defaults:
>
> funcs = []
>
> def create_func(i):
>     return lambda: i
>
> for i in xrange(10):
>     funcs.append(lambda i=i: i)
>     funcs.append(create_func(i))
>
> for f in funcs:
>     print f()

i tried to understand, and maybe i have understood a thing or two...

funcs = []

def create_func(i):
    return lambda: i

for i in xrange(10):
    funcs.append(lambda i=i: i)
    funcs.append(create_func(i))
    funcs.append(lambda: i)            # this is my addition

for f in funcs:
    print f()

ok, i'll try again following your advice

thank you very much
                                                        g
-- 
"It will be rain tonight."
            "Let it come down."



More information about the Python-list mailing list