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

走远了吗. 提交于 2020-07-03 02:47:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!