Changing the colour on click of a tkinter rectangle on click in python

SyShiv picture SyShiv · May 28, 2015 · Viewed 17.5k times · Source

So I have this code which 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've been looking everywhere, and can't seem to find a way to change the fill colour at all, and ideally I'd like to be able to do this on click.

I'm actually going to be using this to change the colour of hexagons generated by a function I wrote that works fine using

create_polygon()

but I imagine it'll work identically with a rectangle.

I realise the code may need to be completely restructured.

Answer

Joel Hinz picture Joel Hinz · May 28, 2015

Name it and then refer to it through itemconfig, like this:

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