Search code examples
pythonarraysuser-interfacebuttontkinter

Get the index of a button (while pressing) which is in an array


I have saved some buttons in an array:

buttons = []
labels.append(tk.Label(fr2, text="", pady=15))
labels.append(tk.Label(fr3, text="", pady=15))

Later I access to a table of a database and loop this table with "for in" so I get all rows from the table in my program. For each row I activate a button with grid.

i = 0
    if len(records) > 0:
        for row in records:
            print("current_date", ", target date")
            print(current_date, row[2])

            date = current_date - row[2]

            labels[i] = tk.Label(fr2, text=row[1], pady=15)
            labels[i].grid(row=i, column=0, sticky='we')
            labels[i+1] = tk.Label(fr3, text=date, pady=15)
            labels[i+1].grid(row=i, column=0, sticky='we')
            buttons[i] = tk.Button(fr4, text="Restart", command=restart, pady=13)
            buttons[i].grid(row=i, column=0, sticky='we')
            buttons[i+1] = tk.Button(fr5, text="Delete", command=delete, pady=13)
            buttons[i+1].grid(row=i, column=0, sticky='we')

            i = i + 1

How can I get the index of the button I put on when the program is running?


Solution

  • you can pass argument to the function you use as command.

    example:

    def myButttonCommand(index):
    
       print("this is the "+index+"th' button")
    
    buttons = []
    
    for i in range (0,10):
    
       buttons[i] = tk.Button(command=myButtonCommand(i))