0

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)
Clipz
  • 11
  • 4
  • There are many questions on this site like this. Have you done any research? – Bryan Oakley Mar 22 '22 at 21:23
  • You can configure the buttons like this: `self.button[i, j].config(...)` But it's not clear to me what exactly is your problem. – Tom Mar 22 '22 at 21:23
  • I did the research and nothing I found helped, the self.button[i, j].config(...) method doesn't work either. I wanted to change the background color of the clicked button using the same function that changes the label on it. – Clipz Mar 22 '22 at 21:31

1 Answers1

0

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')
Clipz
  • 11
  • 4