Array of buttons in python

I want to create a button grid that will switch color when clicked. Currently, each button launches the lower right button. Below is the code. Two questions, why does he do it and how to fix 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 
+4
source share
1 answer

I understood that. Replace:

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

FROM

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

Sorry if this was unpleasant for anyone.

+5
source

Source: https://habr.com/ru/post/1495269/


All Articles