Tkinter Menus

Eric Brunel eric.brunel at pragmadev.com
Thu Dec 12 04:02:23 EST 2002


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()
------------------

- you can also use a class to define your callback. I once defined one 
called GenericCallback that has had many extensions. You can find all of 
them via Google:
http://groups.google.com/groups?hl=en&lr=&ie=ISO-8859-1&q=GenericCallback&meta=group%3Dcomp.lang.python.*

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list