Python - How to change the color of one button in a list of buttons

后端 未结 1 1853
陌清茗
陌清茗 2021-01-27 05:54

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 ==          


        
相关标签:
1条回答
  • 2021-01-27 06:18

    Question: How to access one Button in a grid of Button.

    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).

    • The Tkinter Grid Geometry Manager
    • 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 of tk.Button. Replace tk.Button with tk.Canvas.

    0 讨论(0)
提交回复
热议问题