简体   繁体   English

在python中单击时单击tkinter矩形时更改颜色

[英]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.我意识到代码可能需要完全重组。

Name it and then refer to it through itemconfig , like this:命名它,然后通过itemconfig引用它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM