Creating Tkinter buttons in a loop and setting the command for each button to take in the indices of the loop

Question:

 def run_game(self):

        root = Tk()

        for i in range(0, 6):
            for j in range(0, len(self.board[i])):
            
                button = Button(root, text="0", height=2, width=10, command=lambda: self.if_clicked_square(i,j))
                button.place(x=25 + (100 * j), y=100 + (100 * i))

                # button.pack()
                self.buttonsList[i].append([button])

        root.mainloop()

The above function is creating a GUI board consisting of 28 buttons using Tkinter. I used nested for loops to create every button and place it on the board and also in a list of buttons. The problem arises when setting the command for each button. I want to use the function if_clicked_square(i,j)for the command. The function uses the i and j indices to operate. The problem is that the command for every single button after the loop is done is if_clicked_square(5,2), which happen to be the last indices of the loop. I want every button to have a unique command based on the indices of the for loop. For example, one of the buttons should have the command if_clicked_square(0,0), one should have the command if_clicked_square(1,0), and so forth for all 28 buttons. Can I get any tips to accomplish this?

Asked By: Aaroh Gokhale

||

Answers:

You need to create a local variable in lambda when using a loop

button = Button(root, text="0", height=2, width=10, command=lambda x_p=i,y_p=j: self.if_clicked_square(x_p,y_p))
button.place(x=25 + (100 * j), y=100 + (100 * i))
Answered By: user15801675
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.