Tkinter Menus
Tim Daneliuk
tundra at tundraware.com
Fri Dec 13 21:17:17 EST 2002
Eric Brunel wrote:
> Tim Daneliuk wrote:
>
>>I have a working Tkinter Menubutton/Menu pair. I am associating the same
>>function (command) with each entry in the menu. What I cannot seem to
>>find a way to do is have this single function determine which menu item
>>was actually selected so it can act accordingly.
>>
>>The reason I need to do things this way is that the menu contents is
>>determined at runtime and can vary. It is therefore not practical to
>>have a separate function for each menu entry since I don't know ahead
>>of time how many there will be and what they will be doing ... the
>>association between a menu item and corresponding action will be defined
>>by the user in a configuration file which is read at startup (and which is
>>not written in Python).
>>
>>What am I missing here? ... (Probably something obvious.)
>
>
> AFAIK, nothing in Tk/Tkinter allows to know where the call originated from.
> But there are simple workarounds:
>
> - use lambdas: you can do for example:
>
> ------------------
> from Tkinter import *
> root = Tk()
> b = Menubutton(root, text='Menu')
> b.pack()
> m = Menu(b)
> def callback(i):
> print 'calling', i
> for i in range(5):
> m.add_command(label='Call %s' % (i+1), command=lambda i=i: callback(i+1))
> b.configure(menu=m)
> root.mainloop()
> ------------------
...And this works quite nicely (thank you), but I need some clarification
as to *why* it works, but this does not:
m.add_command(label='Call %s' % (label=" ...", callback(i+1))
There is a semantic subtlety here I think I am missing. I'm guessing that the
lambda comes into being at invocation (menu select event) time, so the evaluation
of (i+1) is deferred until the actual event takes place. But why is this not also
the case in my (non-working) example above which executes at program load time?
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com
More information about the Python-list
mailing list