0

I created a grid of buttons using loops.

for i in range(600//25):
    for j in range(1000//25):
        btns = Button(frame_main , height = 1 , width = 2 , bg = "grey" , command = lambda : clicked(btns , check))
        btns.grid(row = i , column = j)

And I can't seem to add an event to each individual button, it only adds it to the last instance of it, which makes sense, but I don't know how I can reference each and every button individually.

This is the code for the function. It's not complete, but I'm just trying to get the first part to work for each individual button first.

check = 0

def clicked(obj , check):
    if selection_var.get() == 2 :
        if check != 0 :
            messagebox.showerror("Error","You have already selected a start point")
        else :
            check += 1
            obj.config(bg = "green")
Taha
  • 1
  • 2
  • To help solve this problem, can you also provide the `check` function definition, a more detailed description of what it should be doing, and a more detailed description of what it is actually doing instead? Also, check this question and see if it's the cause: https://stackoverflow.com/questions/7546285/creating-lambda-inside-a-loop/7546307 – Multihunter Apr 06 '20 at 05:30
  • 1
    [tkinter-assign-button-command-in-loop-with-lambda](https://stackoverflow.com/questions/17677649/tkinter-assign-button-command-in-loop-with-lambda) may help. – acw1668 Apr 06 '20 at 06:07

1 Answers1

0

You can use sth. like this:

def clicked(i,j):
    # do_stuff

then

class Click:
    def __init__(self, *data):
        self.data = data
    def __call__(self):
        clicked(*self.data)

and finally:

for i in range(600//25):
    for j in range(1000//25):
        btns = Button(frame_main , height = 1 , width = 2 , bg = "grey" , command = Click(i,j))
        btns.grid(row = i , column = j)

Hope that's helpful!

rizerphe
  • 1,340
  • 1
  • 14
  • 24
  • I don't think I quite understood how that works, but I've put the code to the function in as well. Thanks for the help! – Taha Apr 06 '20 at 07:30
  • I define a class. By using `Click(i,j)` I create an object of that class that is callable (`__call__`) and has `data` property set to `(i,j)`, so when the button is clicked, the `__call__` method is called. – rizerphe Apr 06 '20 at 07:34