I\'m trying to change the color of a button. Here is the code.
for i in range(6):
for j in range (6):
if i ==
Question: How to access one
Button
in agrid
ofButton
.
Using .grid(row=i, column=j)
you layout widgets in a Row/Column manner.
To access, one of the widget later on, you can use grid_slaves(row=None, column=None)
.
This implements a OOP
solution, to get your initial approach to work:
mFrame[(3,4)].config(bg= 'red')
class Board(tk.Frame):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
def __getitem__(self, coord):
if isinstance(coord, tuple):
return self.grid_slaves(row=coord[0], column=coord[1])[0]
class Square(tk.Button):
def __init__(self, parent, **kwargs):
# Defaults
kwargs['highlightcolor'] = "black"
kwargs['highlightthickness'] = 1
kwargs['state'] = "disabled"
kwargs['width'] = 11
kwargs['height'] = 5
super().__init__(parent, **kwargs)
Usage
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("800x600")
board = Board(self)
board.grid()
for row in range(6):
for column in range(6):
if row == 0 and column == 0:
square = Square(board, bg='blue', )
elif row == 5 and column == 5:
square = Square(board, bg='red', )
else:
square = Square(board, bg='black', )
square.grid(row=row, column=column)
# Access the Square in Row index 3 and Column index 4,
# using subscript the object `board` by `(3, 4)`.
board[(3, 4)].configure(bg='red')
# Extend, `class Board` to acces the first Square with (1, 1)
# Allow only >= (1, 1) ans subtract 1
# Or Layout Row/Column >= 1, 1
# board[(1, 1)].configure(bg='yellow')
if __name__ == '__main__':
App().mainloop()
Tested with Python: 3.5 - 'TclVersion': 8.6 'TkVersion': 8.6
Note: This will not work on
MACOS
, there you can't change the Background color oftk.Button
. Replacetk.Button
withtk.Canvas
.