Python-如何更改按钮列表中一个按钮的颜色

时间:2019-11-27 13:52:09

标签: python python-3.x tkinter

我正在尝试更改按钮的颜色。这是代码。

for i in range(6):
    for j in range (6):
        if i == 0 and j == 0:
            grids6 = tk.Button(mFrame, bg='blue', highlightcolor="black", highlightthickness=1, state = "disabled", width = 11, height = 5)
             grids6.grid(row = i, column = j)
        elif i == 5 and j == 5:
            grids6 = tk.Button(mFrame, bg='red', highlightcolor="black", highlightthickness=1, state = "disabled", width = 11, height = 5)
            grids6.grid(row = i, column = j)
        else:
            grids6 = tk.Button(mFrame, bg='black', highlightcolor="black", highlightthickness=1, state = "disabled", width = 11, height = 5)
            grids6.grid(row = i, column = j)
grids6[(3,4)].configure(background= 'red') # here is where I tried to change the color but with no success

1 个答案:

答案 0 :(得分:1)

  

问题:如何在Button的{​​{1}}中访问一个grid

使用Button以行/列的方式布置窗口小部件。
要访问稍后提供的小部件之一,可以使用.grid(row=i, column=j)


这实现了grid_slaves(row=None, column=None)解决方案,以使您的最初工作方法得以实现:

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

使用Python测试:3.5-'TclVersion':8.6'TkVersion':8.6

  

注意:这不适用于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() ,因此您无法更改MACOS的背景颜色。将tk.Button替换为tk.Button