passing menu label to function

Peter Otten __peter__ at
Fri Aug 7 21:26:13 CEST 2009

J Wolfe wrote:

> I would like to pass the label name of a menu to the command it is
> calling, is that possible?
>"pass this",command = lambda i =
>"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 =
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)


More information about the Python-list mailing list