0

I used for loop to render 15 buttons, and each button invokes the same function to do something. My question is how to determine which button is clicked? My code snippet is like below:

for number in range(1, 16):
    ttk.Button(bottom_frame, text='Read', command=read_one).grid(column=4, row=number, padx=5, pady=5)

I want to reuse the function read_one() for every button, but don't know how to determine which button is clicked. Any comment is appreciated! Here's my test code: https://pastebin.com/fWyyNVw7

Jo Chen
  • 3
  • 2
  • Turn it into a lambda and store number as a parameter and add a number parameter to your read_one function – Mandera Aug 01 '22 at 02:09
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 01 '22 at 04:10

1 Answers1

2

Since the command callback doesn't get passed any parameters by default (like the calling control), there's no easy option.

However, you could use something like this:

for number in range(1, 16):
    ttk.Button(bottom_frame, text='Read', command=lambda number=number: read_one(number)
        ).grid(column=4, row=number, padx=5, pady=5)

That way, read_one will be called with the number passed. Note that you'd need your read_one function to deal with it, e.g.:

def read_one(number):
    # do something with number, since it tells you what button was pushed
    ...
Grismar
  • 27,561
  • 4
  • 31
  • 54
  • Hi Grismar, thanks for the comment. The lambda function seems evaluate the value of number when any button is clicked, hence no matter what button is clicked, the number is always "15". Here's my test code: https://pastebin.com/fWyyNVw7 – Jo Chen Aug 01 '22 at 04:34
  • 1
    Your solution has the same error of this question "[Tkinter assign button command in loop with lambda](https://stackoverflow.com/questions/17677649/tkinter-assign-button-command-in-loop-with-lambda)". – acw1668 Aug 01 '22 at 04:39
  • @acw1668 thanks for pointing that out, changed the solution, should correctly bind the value now – Grismar Aug 01 '22 at 05:26