Reputation: 1
So after reading a while on lambda event handler it really confused me. for example I have these two lines of code :
b1 = Button(root,text="Show",command=(lambda e=ents :fetch(e)))
root.bind("<Return>",(lambda event, e=ents : fetch(e)))
ents is a function that returns a list of tuples. let's say
[("a",x),("b",y)]
while x
and y
are obtained from an entry (texbox
) just to illustrate my work. fetch is a simple function that prints out the tuples
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print ("%s: %s" %(field,text))
For the first line, lambda took no event argument and we directly gave the context (ents
) , while we used event during the binding. So why do we use an event in one case and we don't in the other ?
Another question, why do we have to assign the list to a variable ( in this case e
) and can't directly use it that way
root.bind("<Return>",(lambda event,ents: fetch(ents)))
because if so, it returns an error : <lambda>() missing 1 required positional argument: 'ents'
Upvotes: 0
Views: 803
Reputation: 9607
The command
parameter of a button is called with no parameters.
The handler for an event binding is called with one parameter, the event itself.
The e=ents
in both lambdas, while technically a parameter, does not require or expect any actual parameter to be passed to the lambda; it's simply an idiomatic way of capturing a value for use in the lambda. You could just as easily written something like lambda: fetch(ents)
. Two slight differences:
e=ents
captures the value of ents
at the time the lambda was defined, any subsequent changes to the value are ignored. That may or may not be relevant here.Upvotes: 2