bilykralik16
bilykralik16

Reputation: 31

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

I would like to ask if it is possible in Python to delete a canvas object which was created with method.
My example code:

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)

However canvas.delete(line2) doesn't work with this way of creating canvas objects.

Is it somehow possible to draw and also delete objects drawn using functions? Thank you for the answers.

Upvotes: 0

Views: 153

Answers (1)

tralph3
tralph3

Reputation: 462

The create functions for the canvas return an identifier that you can use to delete them. What you're doing is correct, except that you're not returning the identifier in your functions. Change the draw functions so that they return the value like so:

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")

Then you'll be able to assign those values to a variable (the same way you're doing it right now) and pass that as an argument to .delete() method:

canvas.delete(line2)

Upvotes: 1

Related Questions