如何在删除 canvas 项时使 ID 再次可用?

How make IDs available again when deleting canvas items?

我想在 canvas 上创建、删除然后再次创建项目。如果新创建的项目与之前的项目具有相同的 ID,那将非常方便。

我试图通过删除带有 canvas.delete(tag) 的项目并删除带有 canvas.dtag(dot, ID-of-dot) 的项目来解决这个问题。到目前为止,注意工作。这里有一个例子来说明我的意思:

import tkinter as tk

root = tk.Tk()

x = 0
y = 25

def oval():
    global x, y
    coords = [x-5, y-5, x+5, y+5]
    if x < 40:
        x += 10
    else:
        x = 10
        canv.delete("dots")
    coords = [x - 5, y - 5, x + 5, y + 5]
    canv.create_oval(*coords, tags="dots")

    dot_list = canv.find_withtag("dots")
    txt.delete(1.0, "end")
    txt.insert(0.0, dot_list)

canv = tk.Canvas(root, width=50, height=50)
canv.grid(row=0, column=0)
but1 = tk.Button(root, width=10, height=1, text="Push Me", command=oval)
but1.grid(row=0, column=1)
txt = tk.Text(width=10, height=1)
txt.grid(row=0, column=2)

root.mainloop()

我想让相同的 ID (1, 2, 3, 4) 重复出现,而不是像这里这样一直计数。有什么办法吗?

编辑

因此,您似乎无法重用 ID,但对于一般解决方案,您可以采用@martineau 的方法并处理 ID-Dict 来分配 ID。 对于这个特定的例子,我发现的一个解决方法是枚举椭圆列表,并将计数作为输出:

txt.delete(1.0, "end")
for i, dot in enumerate(canv.find_withtag("dots")):
    txt.insert("end", i+1)

您不能重复使用 canvas 项 ID。