By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,907 Members | 1,832 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

Tkinter: passing parameters to menu commands

P: n/a
Hi,

I have he following need and do not find an easy way out:

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 ?

Philippe


--
***************************
Philippe C. Martin
SnakeCard LLC
www.snakecard.com
***************************

Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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)
root.config(menu=menu)

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_separator()
filemenu.add_command(label="Exit", command=lambda: callback('Exit'))

mainloop()

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

Kent
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.