Tkinter更新许多对象的画布颜色

2024-09-24 20:38:14 发布

您现在位置:Python中文网/ 问答频道 /正文

有谁能帮我一个忙吗:我有一个字典列表,在那里我储存了未来Tkinter矩形的信息。创建矩形后,我试图使它们根据“x”值的变化而改变颜色,但它仅适用于最后创建的对象,而不适用于其余对象。下面是一个代码:

from tkinter import *

a = {
    "y":2,
    "len" : 4
    }


b = {
    "y":5,
    "len" : 7
    }


c = {
    "y":6,
    "len" : 8
    }


d = {
    "y":2,
    "len" : 4
    }


e = {
    "y":4,
    "len" : 12
    }


f = {
    "y":3,
    "len" : 10
    }


g = {
    "y":7,
    "len" : 10
    }


groupe = [a,d, b, c, g, e, f]

xt1 = 800
xt2= 800
yt1=720
yt2=0

master = Tk()
root = Canvas(master, width=800, height=720)
root.pack()

#Moving RedLine
def deplacer():
    global xt1, yt1, xt2, yt2
    xt1-=5
    xt2-=5
    root.coords(laser_print, xt1, yt1, xt2,yt2)
    root.after(50,deplacer)

    return

#drawing blocks

graf_dist = 0
dist_betw=0
untouched = "blue"
being_touched = "red"
touched= "gray"
block_color=untouched

for ensemble in groupe:

    graf_dist+=60
    dist_betw+=10

    xo=graf_dist+dist_betw
    yo=int(ensemble['y']*50)
    xl=xo+60
    yl=int(ensemble['len']*50)

    if xo<=xt1 and xl>xt1:
        block_color=being_touched
    elif xo<xt1 and xl<=xt1:
        block_color=untouched

    drawing_block = root.create_rectangle(xo, yo, xl, yl, fill=block_color, tag="blocks")


#draw horizontal redline
laser_print=root.create_line(xt1, yt1, xt2, yt2, fill="red")

#updating the color of the rectangles
def update_color():
    x_block=xt1+1
    untouched = "blue"
    being_touched = "red"
    touched= "gray"
    block_color=untouched   

    if xo<=x_block and xl>x_block:
        block_color=being_touched
    elif xo<x_block and xl<=x_block:
        block_color=untouched
    root.itemconfig(drawing_block, fill=block_color)
    root.after(50,update_color)

update_color()
deplacer()
mainloop()

Tags: andlendistrootblockcolorxoxl
1条回答
网友
1楼 · 发布于 2024-09-24 20:38:14

好的,首先,您绘制了七个块,但是它们都被指定给drawing_block。当您在update_color()中引用drawing_block时,这当然是最后一个块

首先需要为每个块创建单独的对象,例如,将它们存储在列表中:

drawing_blocks = []
for ensemble in groups:
...
    drawing_blocks.append(root.create_rectangle(xo, yo, xl, yl, fill=block_color, tag="blocks"))

然后您需要更改update_color()函数来测试激光器是否通过每个单独的块,然后更改特定块的颜色

相关问题 更多 >