# [Tkinter] messed callbacks

Scott David Daniels Scott.Daniels at Acm.Org
Wed Sep 9 16:29:13 CEST 2009

```Giacomo Boffi wrote:
> Giacomo Boffi <giacomo.boffi at polimi.it> writes:
...
> | def create_cb(a,b):
> |     return lambda: output(a+'->'+b)
> |
> | 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=create_cb(c1,c2)).pack()
> |     Button(subframe,text='<',command=create_cb(c2,c1)).pack()
> |     subframe.pack(fill='x',expand=1)
...
> works ok, now i have to fully understand my previous error

This is really why functools.partial exists.  Now that you know what was
going wrong, you can understand its value.  You can accomplish the same
thing as above with:
from functools import partial
...
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=partial(output, c1 + '->' + c2)).pack()
Button(subframe, text='<',
command=partial(output, c2 + '->' + c1)).pack()
subframe.pack(fill='x', expand=1)
...
Also note from Pep 8, spaces are cheap and make the code easier to read.

--Scott David Daniels
Scott.Daniels at Acm.Org

```

More information about the Python-list mailing list