在 tkinter 中独立更改颜色或多个形状

问题描述 投票:0回答:1

我想创建一个程序,可以通过单击鼠标来切换许多方块的颜色。我能够创建形状并切换颜色。

我的问题是有很多方块。我的“改变颜色”功能同时切换所有方块的颜色。我明白原因是我使用相同的标签,但我不知道如何使用具有相同功能的多个标签。

import tkinter
from tkinter import *
import math
from itertools import cycle

# Variables
shot_colors = ['red', 'blue']
scale = 4.04
radius = scale * 50
diameter = 2 * radius
chord_length = scale * 32.5
chord_angle = 37.93
chord_angle_compliment = 360 - chord_angle
x0 = 50
y0 = 50
x1 = x0 + diameter
y1 = y0 + diameter
start = 270 + 0.5 * chord_angle


# Define a function to change the state of the Widget
def change_color(*args, colors=cycle(shot_colors)):
    canvas.itemconfig(tagOrId="shot", fill=next(colors))


root = Tk()
canvas = Canvas(root, width=1000, height=750)

# Create wafer shape, circle with flat oriented down
wafer = canvas.create_arc(x0, y0, x1, y1, start=start, extent=chord_angle_compliment, style=tkinter.CHORD, outline="black",
                  fill="gray", width=2)

# Create shot shapes, rectangle, this will be a for loop to create many shot(s)
shot1 = canvas.create_rectangle(257, 257, 277, 277, outline="black", fill="blue", tag="shot")
shot2 = canvas.create_rectangle(277, 277, 297, 297, outline="black", fill="blue", tag="shot")

# Change color of shot when clicked with mouse
canvas.tag_bind("shot", "<Button-1>", change_color)

canvas.pack()

root.mainloop()
python tkinter tags
1个回答
0
投票

如果您希望绑定仅影响被单击的项目,则可以使用标签“current”。

来自官方画布文档:

标签current由Tk自动管理;它适用于 current 项目,它是最上面的项目,其绘制区域覆盖了鼠标光标的位置(不同的项目类型以不同的方式对此进行解释;有关详细信息,请参阅各个项目类型文档)。如果鼠标不在画布小部件中或不在某个项目上,则没有项目具有 current 标签。

您的函数可以编写为使用此标签,如以下示例所示:

def change_color(*args, colors=cycle(shot_colors)):
    canvas.itemconfig(tagOrId="current", fill=next(colors))
© www.soinside.com 2019 - 2024. All rights reserved.