Max says…

Avatar

thoughts of a web developer

Python Lambda Expressions

I’ve been writing a small Python/Tk application and until recently was having trouble with menu item callback functions.  I have a series of menu items, all of which do much the same thing, but within the context of an item-specific ID.  Therefore it would make sense to have a generic function that takes some parameter to determine what to do.

However, when adding a menu item and callback, e.g.

menu.add_command(label = someLabel, command = someCallback)

you must pass in the name of a function, rather than a function call. To get around this, I used a lambda function to pass in a previously defined value to a callback:

id = some_value
menu.add_command(label = someLabel, command = lambda id=id: someCallback(id))

No Comments, Comment or Ping

Reply to “Python Lambda Expressions”