Changing rectangle color on click in Python using Tk
Question: I'm trying to get a Tk rectangle created on a canvas to change its color when
clicked. Right now, no color change happens when the rectangle is clicked.
What do I need to be doing differently?

This is in Python3.5, by the way.

    
    
    from tkinter import *
    
    
    def set_color(id):
        global alive, colors
        alive = not alive
        col = colors[alive]
        canvas.itemconfigure(id, fill=col)
    
    root = Tk()
    canvas = Canvas(root)
    canvas.grid(column=1, row=1, sticky=(N, S, E, W))
    
    alive = False
    colors = {True: "green", False:  "red"}
    
    id = canvas.create_rectangle((1, 1, 60, 60), fill="red")
    canvas.tag_bind(id, "<ButtonPress-1>", set_color)
    
    
    root.mainloop()
    


Answer: tag_bind sends an event to the function, so "id" is overwritten and now
contains the event. So you can change from

    
    
    def set_color(id):
    ## to
    def set_color(event=None):
    

and it will work because there is only one object/id to deal with in this
program. event=None is used because it assigns a default value when no event
is sent to the function, as in a button press for example, so will work for
all responses.

