13

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.

SyShiv
  • 131
  • 1
  • 1
  • 3

1 Answers1

22

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')
Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
  • This is great if you have a few rectangles only: but this doesn't scale for many shapes - is there an alternative that doesn't make use of the variable name that holds the reference to the rectangle? – monojohnny Jan 06 '16 at 00:13
  • @monojohnny I'm afraid I don't know; I only have limited experience with Tkinter. – Joel Hinz Jan 06 '16 at 09:04
  • Actually - it isn't the name that is important - it's the reference to the object itself - so your method works just great - and does in fact scale just fine I would say. (I thought the name of the variable was special, but actually it's what the variable points at that is used), Cheers! – monojohnny Jan 06 '16 at 11:46
  • 2
    @monojohnny you could create a list of these objects instead of variables for each of them. By doing this, later you could iterate with this list and do whatever you want. Would this be a better solution? – Felipe Jul 04 '18 at 07:34