Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On python, how do I determine which button was clicked

How would I run an if statement to determine which button was clicked? I've been looking around, but I am new to Tkinter and I'm not too sure what I'm supposed to do.

    self.button1 = Tkinter.Button(self,text=u"Convert Decimal to Binary", command=self.OnButtonClick)
    self.button1.grid(column=1,row=1)

    self.button2 = Tkinter.Button(self,text=u"Convert Binary to Decimal", command=self.OnButtonClick)
    self.button2.grid(column=1,row=2)
like image 733
Dan Avatar asked Jan 21 '26 03:01

Dan


2 Answers

You could set each button's command option to a lambda like this:

self.button1 = Tkinter.Button(self, ..., command=lambda: self.OnButtonClick(1))
...
self.button2 = Tkinter.Button(self, ..., command=lambda: self.OnButtonClick(2))

Then, make self.OnButtonClick accept an argument that will be the button's "id". It would be something like this:

def OnButtonClick(self, button_id):
    if button_id == 1:
        # self.button1 was clicked; do something
    elif button_id == 2:
        # self.button2 was clicked; do something

An object-oriented way to do this is to just pass the button clicked to theOnButtonClick()method:

    def OnButtonClick(self, button):
        # do stuff with button passed...
        ...

In order to do this requires creating and configuring each button in two steps. That's necessary because you need to pass the button as an argument to the command which can't be done in the same statement that creates the button itself:

    button1 = Tkinter.Button(self, text=u"Convert Decimal to Binary")
    button1.config(command=lambda button=button1: self.OnButtonClick(button))
    button2 = Tkinter.Button(self, text=u"Convert Binary to Decimal")
    button2.config(command=lambda button=button2: self.OnButtonClick(button))
like image 42
martineau Avatar answered Jan 23 '26 15:01

martineau