Color change when clicking tkinter rectangle when clicking on python

So, I have this code that draws a simple rectangle:

from tkinter import *

root = Tk()
canvas = Canvas(root, width = 500, height = 500)
canvas.pack()

canvas.create_rectangle(100, 100, 400, 400, fill='black')


mainloop()

Now I searched everywhere and cannot find a way to change the fill color at all, and ideally I would like to do this when clicked.

I really use this to change the color of the hexagons generated by the function I wrote, which works fine with

create_polygon()

but I think it will work the same with the rectangle.

I understand that the code can be completely restructured.

+4
source share
1 answer

Name it, and then refer to it through itemconfig, for example:

myrectangle = canvas.create_rectangle(100, 100, 400, 400, fill='black')
canvas.itemconfig(myrectangle, fill='red')
+8
source

All Articles