DrBwts
DrBwts

Reputation: 3657

Tkinter changes the wrong button background when button pressed

I have an array of buttons, when I press a button the button's position in the array is printed but the color is not changed. Instead the color of the button at the bottom of the respective column is changed. Here I have pressed 0, 0, 1, 0 & 2, 4, as can be seen the buttons at the bottom of each column have changed but not the button pressed with the exception of 2, 4.

How come?

enter image description here

The code,

from tkinter import *

def init():
    print("Started")

class App:

    def __init__(self, master):

        self.text = [[None]*50]*3
        self.buttons = [[None]*50]*3
        frame = Frame(master)
        #frame.pack()
        
        for i in range(3):
            
            for j in range(50):
                
                self.buttons[i][j] = Button(root, command = lambda i=i, j=j : self.led(i, j))
                self.buttons[i][j].config(width = 2, height = 3)
                self.buttons[i][j].grid(row = i, column = j)
        
    def led(self, i, j):
        print(i, j)
        self.buttons[i][j].config(bg = 'blue')
        
        
init()
root = Tk()
app = App(root)
root.mainloop()

Upvotes: 0

Views: 78

Answers (1)

Yulia V
Yulia V

Reputation: 3559

When you run the lines

self.text = [[None]*50]*3
self.buttons = [[None]*50]*3

your lists contain 3 instances of the same array. Using

[[None]*50 for _ in range(3)]

should create a list that contains 3 different instances of lists.

Upvotes: 2

Related Questions