passing menu label to function

J

J Wolfe

Hi,

I would like to pass the label name of a menu to the command it is
calling, is that possible?

self.menuitem.menu.add_command(label="pass this",command = lambda i =
self.self.menuitem.menu.cget("label"): self.function(i))

def function(self, i)
print i # print the label name


Any help would be appreciated!
Thanks!
Jonathan
 
P

Peter Otten

J said:
I would like to pass the label name of a menu to the command it is
calling, is that possible?

self.menuitem.menu.add_command(label="pass this",command = lambda i =
self.self.menuitem.menu.cget("label"): self.function(i))

def function(self, i)
print i # print the label name

A simple pure-python approach:

def add_command_with_label(menu, label, command):
menu.add_command(label=label, command=lambda: command(label))

# ...

function = self.function
menu = self.menuitem.menu
add_command_with_label(menu, "pass this", function)

Alternatively, if you plan to change the labels during runtime:

index = 1 # indices start at 1, not 0
menu.add_command(label="whatever", command=lambda index=index, menu=menu:
function(menu.entrycget(index, "label")))

(all untested, likely to contain typos)

Peter
 
J

J Wolfe

Thanks Peter,

I figured out an alternative just as you posted your response,

I just looped through the buttons I wanted to add and used the loop
variable to label the item and then passed it to the function, though
your way seems much more robust.

Thanks a lot!
 

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
474,274
Messages
2,571,366
Members
48,052
Latest member
EvaW192252

Latest Threads

Top