Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 379
SyShiv Avatar asked May 28 '15 13:05

SyShiv


1 Answers

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')
like image 160
Joel Hinz Avatar answered Dec 01 '22 15:12

Joel Hinz