11

I want to create a grid of buttons that will toggle colour when they are clicked. At the moment every button will trigger the bottom right button instead. Below is the code. Two questions, why is it doing this and how do I correct it?

def main(self):
    root = Tk()
    frame=Frame(root)
    frame.grid(row=0,column=0)

    self.btn=  [[0 for x in xrange(20)] for x in xrange(60)] 
    for x in range(60):
         for y in range(20):
            self.btn[x][y] = Button(frame,command= lambda: self.color_change(x,y))
            self.btn[x][y].grid(column=x, row=y)

     root.mainloop()

def color_change(self,x,y):
    self.btn[x][y].config(bg="red")
    print x,y
whossname
  • 679
  • 1
  • 6
  • 17

1 Answers1

16

I figured it out. Replace:

    self.btn[x][y] = Button(frame,command= lambda: self.color_change(x,y))

With:

 self.btn[x][y] = Button(frame,command= lambda x1=x, y1=y: self.color_change(x1,y1))

Sorry if this was a nuisance to any one.

whossname
  • 679
  • 1
  • 6
  • 17
  • 4
    you know, int the `lambda`, you can just do `x=x, y=y`. The variables in the lambda don't have to be different. – The-IT Aug 05 '13 at 10:50