问题
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.
回答1:
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')
来源:https://stackoverflow.com/questions/30507986/changing-the-colour-on-click-of-a-tkinter-rectangle-on-click-in-python