Tkinter Menus

Justin Shaw wyojustin at hotmail.com
Fri Dec 13 22:38:58 EST 2002


"Tim Daneliuk" <tundra at tundraware.com> wrote in message
news:m74eta.vjq2.ln at boundary.tundraware.com...
> 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
>

This version invokes callback when the menu is created:
m.add_command(label='Call %s' % (label=" ...",  callback(i+1))

and so is essentially the same as
m.add_command(label='Call %s' % (label=" ...",  None)

as apposed to the other version which creates a lambda function at menu
creation time that gets called when the menu is clicked.







More information about the Python-list mailing list