简体   繁体   English

Python(Tkinter)-画布for循环颜色更改

[英]Python (Tkinter) - canvas for-loop color change

I generated a grid using a for-loop in Tkinter, but want to know how I would be able to bind an on-click function to such that when I click on each individual generated rectangle, the rectangle will change color. 我在Tkinter中使用for循环生成了一个网格,但想知道如何将一个单击函数绑定到,以便当我单击每个生成的矩形时,矩形将改变颜色。

from Tkinter import *

master = Tk()

def rowgen(row, col):
    for i in range(row):
        for j in range(col):
            w.create_rectangle(25+50*i, 25+50*j, 50+50*i, 50+50*j, fill="green")

w = Canvas(master, width=225, height=225)
w.pack()
rowgen(4, 4)


master.resizable(0,0)
mainloop()

I'm thinking that I have to first iterate through another for-loop to make an event, where if I click within these coordinates, I'd reconfig the color of one of the rectangles. 我在想,我必须首先遍历另一个for循环来创建一个事件,如果我在这些坐标内单击,则会重新配置其中一个矩形的颜色。

By following Curly Joe's hints and making some mistakes, I got the following, which requires only one tag_bind. 通过遵循Curly Joe的提示并犯了一些错误,我得到了以下内容,它只需要一个tag_bind。 You might want to try it yourself first. 您可能想先自己尝试一下。

from tkinter import *

master = Tk()

def box_click(event):
    box = event.widget.find_closest(event.x, event.y)
    print(box)  # remove later
    w.itemconfig(box, fill='red')

def rowgen(row, col):
    for i in range(row):
        for j in range(col):
            w.create_rectangle(25+50*i, 25+50*j, 50+50*i, 50+50*j,
                               fill="green", tag='BOX')

w = Canvas(master, width=225, height=225)
w.pack()
rowgen(4, 4)
w.tag_bind('BOX', '<Button-1>', box_click)

master.resizable(0,0)
mainloop()

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

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