Parameterized functions of no arguments?

Rotwang sg552 at hotmail.co.uk
Fri Feb 11 06:26:18 CET 2011


On 11/02/2011 04:54, Rotwang wrote:
> Hi all
>
> Sorry if this is a dumb question, I would guess it's answered in an FAQ
> somewhere but I haven't been able to find anything that helps. I'm
> trying to use Tkinter to create a menu whose entries and corresponding
> commands depend on some list x. I want the menu options to be labelled
> by the elements of x, and upon selecting an option k I want my program
> to execute a function f(k). So I tried writing something that
> schematically looked like this:
>
>     def f(k):
>         [do something that depends on k]
>
>     menu = Tkinter.Menu(master, tearoff = 0)
>     for k in x:
>         menu.add_command(label = str(k), command = lambda: f(k))
>
> The trouble is, whenever I open the menu and click on any entry k,
> instead of evaluating f(k) it always evaluates f(x[-1]). I've also tried
> this:
>
>     menu = Tkinter.Menu(master, tearoff = 0)
>     for k in x:
>         def f():
>             [do something that depends on k]
>         menu.add_command(label = str(k), command = f)


Mmmmnngh, that obviously wasn't going to work. Here's something that 
does work:

     menu = Tkinter.Menu(master, tearoff = 0)
     for k in x:
         def f(j = k):
             [do something that depends on j]
         menu.add_command(label = str(k), command = f)

Still, I'd like to know if there's a more elegant method for creating a 
set of functions indexed by an arbitrary list.



More information about the Python-list mailing list