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)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With