Why is lambda expression necessary in this example? (Python) -


i'm learning little bit of tkinter in python, creating interactive windows. window i'm making 1 that, given dict of contacts , respective contact info, creates button each contact which, when pressed, displays contact info.

the 2 sample contacts have named 'marvin' , 'minsky', , info stored in dict named book:

import tkinter tkinter  # 'phonebook' contact info 2 people. book = {"marvin": {"mobile": "1234567890", "email": "marvin@gmail.com"},  "minsky": {"mobile": "9087865342", "email": "minsky@yahoo.com"}}   window = tkinter.tk() # make window object  def showinfo(name):   # displays info person button clicked    # displays info configuring labels named 'mobile' , 'email',    # using values in 'book'   mobile.configure(text = book[name]["mobile"])   email.configure(text = book[name]["email"]) 

here's important part. instead of buttons using command = showinfo(name) call showinfo(), first tried, lambda expression used:

for name in sorted(phonedict.book.keys()):    # create button each alphabetically sorted name   btn = tkinter.button(text = name, command = lambda arg = name: showinfo(arg))   btn.pack() 

and rest of code labels showinfo() modifies:

# window section contact info displayed via labels mobile_lbl = tkinter.label(text = "mobile:") mobile_lbl.pack() mobile = tkinter.label(text = "") mobile.pack() email_lbl = tkinter.label(text = "email:") email_lbl.pack() email = tkinter.label(text = "") email.pack()  # display window window.mainloop() 

when run, program want do, modifying labels correctly when each button clicked.

if command = showinfo(name) used in place of lambda, however, nameerror: global name 'mobile' not defined thrown because (i think) tries execute button's command when button created instead of when pressed.

why use of lambda expression in button's command keep command executing until button clicked? functional purpose serving?

like guessed, when use command = showinfo(name) asking python immediately call showinfo(name), , assign result of command attribute.

the command attribute must given reference function. lambda convenient way create anonymous function , return reference, gets assigned attribute. inside anonymous function can call other function want, , inner code isn't executed until anonymous function executed.

the functional purpose of lambda create temporary, unnamed function can passed other functions or stored attribute. convenient way (but not way1) create wrapper around callback requires argument.

1another way accomplish same thing functools.partial. method write own decorator.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -