Tkinter: passing parameters to menu commands

  • Thread starter Philippe C. Martin
  • Start date
P

Philippe C. Martin

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
***************************
 
K

Kent Johnson

Philippe said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top