我创建了一个Tkinter网格,并希望为网格的不同单元格设置不同的背景颜色。
我怎样才能做到这一点?
答案 0 :(得分:0)
我像这样创建网格:
import numpy as np
from tkinter import *
M = np.array([[1, 2], [3, 4]])
root = Tk()
for i in range(len(M)): #Rows
for j in range(len(M[0])): #Columns
b = Label(root, text=str(M[i][j]))
b.grid(row=i, column=j)
mainloop()
答案 1 :(得分:0)
最近有同样的问题!我认为您需要提供更多详细信息,但这是一个一般性的答案以及对我有用的方法:
(示例),假设您要在两个for循环中定义小部件,如下所示:
widgets_dictionary = {} # initialize your empty dictionary
for i in range(rows):
for j in range(columns):
# widget definition here, let's say it's a label
label = Label(...)
label.pack()
# create a reference to the widget in your dictionary
widget[(i,j)] = label
# Now, referring to your specific question:
# (x,y) = the index of the cell you want to change
# colour = the background colour you want to change it to
widget[(x,y)].config(bg = "colour")
希望这会有所帮助! :)