[Tutor] Tk -- which label clicked

jfouhy@paradise.net.nz jfouhy at paradise.net.nz
Fri Jul 15 13:29:22 CEST 2005


Quoting Michael Lange <klappnase at freenet.de>:

> I don't think it will work this way, because you don't catch the event
> bind() passes to the callback
> (you also use a variable "e" in makeCallback() that isn't defined
> anywhere).

That's what the variable 'e' is doing!

Here is some code I just wrote and tested:

>>> def clicked(w):
...  print 'Widget %s clicked! Text: %s' % (str(w), w.cget('text'))
...
>>> def makeCallback(w):
...  def callback(e):
...   clicked(w)
...  return callback
...
>>> from Tkinter import *
>>> tk = Tk()
>>> for text in ['foo', 'bar', 'baz']:
...  lb = Label(tk, text=text)
...  lb.pack()
...  lb.bind('<Button-1>', makeCallback(lb))
...
'11427352callback'
'12096856callback'
'12097016callback'
>>> # Now to click on the labels.
Widget .11444992 clicked! Text: foo
Widget .12097096 clicked! Text: bar
Widget .12097336 clicked! Text: baz
Widget .12097096 clicked! Text: bar
Widget .11444992 clicked! Text: foo

-----------------

Lambdas are (probably) going away in Py3000, so I am trying to get away from
using them (it's hard, though :-) ).  Anyway, makeCallback() defines a function
which takes one argument (that's the event), and then calls clicked() on the
widget argument to makeCallback().  That function is returned and bound to
<Button-1>.

Here's a simpler example of the same thing:

>>> def add(x):
...  def addx(y):
...   return x + y
...  return addx
...
>>> f = add(5)
>>> f(3), f(5), f(9)
(8, 10, 14)

(of course, I could have done the same thing by writing: f = (5).__add__ ...)

-- 
John.


More information about the Tutor mailing list