Reputation: 51
I am a beginner to tkinter and I was trying to create a 5X5 grid of buttons using a 2D list. But if I try to change the bg colour of the button after the for loop, it only changes the colour of the buttons of the last row.
from tkinter import *
rows=5
columns=5
btns=[[None]*5]*5
root=Tk()
def darken(btn):
btn.configure(bg='black')
for i in range(rows):
for j in range(columns):
btns[i][j]=Button(root,padx=10,bg='white')
btns[i][j]['command']=lambda btn=btns[i][j]:darken(btn)
btns[i][j].grid(row=i,column=j)
btns[0][0]['bg']='yellow'
root.mainloop()
Upvotes: 1
Views: 379
Reputation: 1439
The problem is in the way you construct the list
btns=[[None]*5]*5
in this way you create a list and moltiplicate its reference per 5 times. As this each time that it loops for add a button in the row list the same changes affects the other row lists.
EX
btns = [[None]*5]*5
btns[0][0] = 'a'
btns ---> [
['a', None, None, None, None],
['a', None, None, None, None],
['a', None, None, None, None],
['a', None, None, None, None],
['a', None, None, None, None]
]
This is the correct way of build the list
btns = [[None for i in range(rows)] for j in range(columns)]
Upvotes: 1