在python中单击时单击tkinter矩形时更改颜色 [英] Changing the colour on click of a tkinter rectangle on click in python

查看:41
本文介绍了在python中单击时单击tkinter矩形时更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个代码绘制一个简单的矩形:

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.

推荐答案

命名然后通过itemconfig引用,像这样:

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')

这篇关于在python中单击时单击tkinter矩形时更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆