Search code examples
pythontkintertkinter-button

tkinter multiple buttons invoke same function, how to determine the clicked one?


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


Solution

  • 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
        ...