0

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.

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.