Tkinter: passing parameters to menu commands

Kent Johnson kent3737 at
Fri Jan 7 15:50:03 EST 2005

Philippe C. Martin wrote:
> I have many menu items and would like them all to call the same method
> -However, I need the method called to react differently depending on the
> menu item selected. Since the menu command functions do not seem to
> receive any type of event style object, is there some type of Tkinter
> call that would let my method know the menu id selected ?

Much as it seems to be out of favor, IMO this is a place where a lambda expression is very handy. 
You can make a callback for each menu item that binds an extra parameter to the handler:

# Based on an example by Fredrik Lundh
from Tkinter import *

def callback(code):
     print "called the callback with code", code

root = Tk()

# create a menu
menu = Menu(root)

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=lambda: callback('New'))
filemenu.add_command(label="Open...", command=lambda: callback('Open'))
filemenu.add_command(label="Exit", command=lambda: callback('Exit'))


Of course you could do this with named forwarding functions if you prefer.


More information about the Python-list mailing list