0

I have a list of buttons and when I run a function I need to check what button in that list was pressed.

import tkinter

root = tkinter.Tk()

def Function(event):
    print('The pressed button is:')

listOfButtons = []
Button = tkinter.Button(root, text="Button 1")
listOfButtons.append(Button)
Button.pack()
Button.bind("<Button-1>", Function)

Button = tkinter.Button(root, text="Button 2")
Button.pack()
listOfButtons.append(Button)
Button.bind("<Button-1>", Function)

root.mainloop()
j_4321
  • 15,431
  • 3
  • 34
  • 61
Green_Boy03
  • 3
  • 1
  • 2
  • 2
    You don't need to use `bind` on buttons, just use their `command` option when you create them. – j_4321 Dec 19 '17 at 09:34
  • Not only you don't need to use `bind` but you're limitating your button to able to run `Function` if and only if it is pressed using mouse left click. – Nae Dec 19 '17 at 09:37

2 Answers2

3

Iterate over all buttons in the list, and check if button is event.widget:

def Function(event):
    for button in listOfButtons:
        if button is event.widget:
            print(button['text'])
            return

As @tobias_k mentioned - it's overcomlicated. You already has a button as event.widget. So solution is simple as print(event.widget['text']). However, if Function can be called not only from the button click or there're several lists with buttons/with whatever - it's a must to check!

In other side, button can be pressed not only by the Left-mouse click, hence command option is better!

import tkinter

root = tkinter.Tk()

def Function(button):
    print(button['text'])


...
Button = tkinter.Button(root, text="Button 1")
Button.configure(command=lambda button=Button: Function(button))
...


Button = tkinter.Button(root, text="Button 2")
Button.configure(command=lambda button=Button: Function(button))
...

root.mainloop()
CommonSense
  • 4,232
  • 2
  • 14
  • 38
1

You can use command

import tkinter

root = tkinter.Tk()

def Function(event):
    if event == 1:
        print('The pressed button is: 1')
    if event == 2:
        print('The pressed button is: 2')

listOfButtons = []
Button = tkinter.Button(root, text="Button 1", command= lambda: Function(1))
listOfButtons.append(Button)
Button.pack()

Button = tkinter.Button(root, text="Button 2",command= lambda: Function(2))
Button.pack()
listOfButtons.append(Button)

root.mainloop()
Alper Fırat Kaya
  • 2,079
  • 1
  • 18
  • 18
  • 2
    You need to do `command= lambda: Function(1)` otherwise, you execute the function on button creation, not when it is clicked. – j_4321 Dec 19 '17 at 09:41
  • You are right ,i corrected it.I was thinking that something is wrong and found the answer at https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter and saw the command :D – Alper Fırat Kaya Dec 19 '17 at 09:47