'Changing background color to buttons generated in a for loop

I am making a tic tac toe GUI using Tkinter and buttons. Got over some stuff and now I wanted to change the background color when one of the buttons is clicked. The things I did so far I did with lambda but now I can seem to find a way to use the config option of the Button function from Tkinter. I wanted to add that configuration in the which_button function but nothing I could find would help me.

def __init__(self):
    super().__init__()
    self.button = {}
    self.turn = 'X'
    for i in range(3):
        for j in range(3):
            self.button[i, j] = Button(root, width=10, height=5, bg='#E0E0E0', fg='#6D6D6D', command=lambda i=i, j=j: self.which_button(i, j),).grid(row=i, column=j)

def which_button(self, i, j):
    label = Label(root, text=self.turn, fg='#E0E0E0', bg='#6D6D6D')
    label.grid(row=i, column=j)


Solution 1:[1]

If someone is searching for the same thing the problem was that the buttons could configure because they weren't even saved anywhere. My solution was to create a separate function to create buttons with a return statement to initially save the buttons and then using tuples call those buttons to configure them.

def __init__(self):
    super().__init__()
    self.button = {}
    self.turn = 'X'
    for i in range(3):
        for j in range(3):
            self.button[(i,j)]=self.create_button(i, j)

def create_button(self, x, y):
    self.button1 = Button(root, width=10, height=5, bg='#E0E0E0', fg='#6D6D6D', command=lambda i=x, j=y: self.pressed_button(i, j),)
    self.button1.grid(row=x, column=y)
    return self.button1

def pressed_button(self, i, j):
    label = Label(root, text=self.turn, fg='#E0E0E0', bg='#6D6D6D')
    label.grid(row=i, column=j)
    self.button[(i, j)].configure(bg='#6D6D6D')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Clipz