Ammi
Ammi

Reputation: 15

Can I recognize label content in popup menu as an argument?

I created a lots of menu in tkinter,every menu has its corresponding command,so I have to creat a number of command functions.

If the label content can be an argument then I can pass it to only one function.How can I make it become an argument?

def show_rc_menu(self,event):
    self.menu.post(event.x_root, event.y_root)
def creat_right_click_menu(self):
    self.menu=Menu()
    self.menu.add_command(label='hereiam1',command=self.hello)
    self.menu.add_command(label='hereiam2',command=self.hello)
    self.menu.add_command(label='hereiam3',command=self.hello)
    ...
    self.menu.add_command(label='hereiam100',command=self.hello)
def resize(self,e):
    print e

Upvotes: 1

Views: 51

Answers (2)

Kenly
Kenly

Reputation: 26698

Use lambda just with one command:

def hello(text=None):
   if text:
      # Do some things

self.menu=Menu()
self.menu.add_command(label='hereiam1',command=lambda :self.hello('some_text'))
self.menu.add_command(label='hereiam2',command=self.hello)
self.menu.add_command(label='hereiam3',command=self.hello)

Upvotes: 1

tobias_k
tobias_k

Reputation: 82899

You can not influence the parameters that the menu button or another widget will pass into the callback function by itself (none, in this case), but you can use a lambda function to pass a parameter:

self.menu.add_command(label='hereiam1', command=lambda: self.hello('hereiam1'))

and similarly for the other buttons. Then, in your callback function, you test this parameter and execute the different actions:

def hello(self, hint):
    if hint == "hereiam1":
        print("do stuff for hereiam1")
    elif hint == ...:
        ...

However, unless all those callbacks are very similar, I'd suggest actually using different callback functions for the different menu buttons.

Upvotes: 0

Related Questions