Python (Tkinter) - canvas for-loop color change
Question: I generated a grid using a for-loop in Tkinter, but want to know how I would
be able to bind an on-click function to such that when I click on each
individual generated rectangle, the rectangle will change color.

    
    
    from Tkinter import *
    
    master = Tk()
    
    def rowgen(row, col):
        for i in range(row):
            for j in range(col):
                w.create_rectangle(25+50*i, 25+50*j, 50+50*i, 50+50*j, fill="green")
    
    w = Canvas(master, width=225, height=225)
    w.pack()
    rowgen(4, 4)
    
    
    master.resizable(0,0)
    mainloop()
    

I'm thinking that I have to first iterate through another for-loop to make an
event, where if I click within these coordinates, I'd reconfig the color of
one of the rectangles.


Answer: By following Curly Joe's hints and making some mistakes, I got the following,
which requires only one tag_bind. You might want to try it yourself first.

    
    
    from tkinter import *
    
    master = Tk()
    
    def box_click(event):
        box = event.widget.find_closest(event.x, event.y)
        print(box)  # remove later
        w.itemconfig(box, fill='red')
    
    def rowgen(row, col):
        for i in range(row):
            for j in range(col):
                w.create_rectangle(25+50*i, 25+50*j, 50+50*i, 50+50*j,
                                   fill="green", tag='BOX')
    
    w = Canvas(master, width=225, height=225)
    w.pack()
    rowgen(4, 4)
    w.tag_bind('BOX', '<Button-1>', box_click)
    
    master.resizable(0,0)
    mainloop()
    

