是否可以删除使用 Python 中的函数创建的 canvas 对象?

Is it possible to delete canvas object created with a function in Python?

我想请问是否可以在Python中删除使用方法创建的canvas对象。
我的示例代码:

import tkinter
window = tkinter.Tk()
canvas = tkinter.Canvas(width=1000, height=600, bg="black")
canvas.pack()

def draw_yellow(x1, y1, x2, y2):
    canvas.create_line(x1, y1, x2, y2, fill="yellow")

def draw_white(x1, y1, x2, y2):
    canvas.create_line(x1, y1, x2, y2, fill="white")

line1 = draw_yellow(20, 300, 100, 300)
line2 = draw_white(20, 300, 100, 300)
line3 = draw_white(40, 200, 60, 200)
canvas.delete(line2)

但是 canvas.delete(line2) 不适用于这种创建 canvas 对象的方式。

是否可以通过某种方式绘制和删除使用函数绘制的对象?谢谢你的回答。

canvas return 标识符的创建函数可用于删除它们。你所做的是正确的,只是你没有 return 在你的函数中使用标识符。更改绘图函数,使它们 return 值如下所示:

def draw_yellow(x1, y1, x2, y2):
    return canvas.create_line(x1, y1, x2, y2, fill="yellow")

def draw_white(x1, y1, x2, y2):
    return canvas.create_line(x1, y1, x2, y2, fill="white")

然后您将能够将这些值分配给一个变量(与您现在所做的方式相同)并将其作为参数传递给 .delete() 方法:

canvas.delete(line2)