Delete an object on the canvas

How to delete an object

If you give a label to an object you draw on the canvas, you can delete it with the method `delete` of canvas object itself. Let’s use the code of the last lesson, to see how can we use it pratically.

# delete on cavas

rectangle1 = canvas.draw_rectangle((0,0,10,10), fill='blue')
canvas.delete(rectangle1)

Let’s see the example (sort of game)

# a game with tkinter and canvas

import tkinter as tk

root = tk.Tk()

WIDTH = HEIGHT = 400

x1 = y1 = WIDTH / 2

canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()

c1 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10)
c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10)


def draw_rect():
    global c2
    canvas.delete(c2)
    c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="green")


def del_rect():
    canvas.delete(c1)
    #canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="white", opacity=0.5)


def move(event):
    global x1, y1
    if event.char == "a":
        del_rect()
        x1 -= 10
    elif event.char == "d":
        del_rect()
        x1 += 10
    elif event.char == "w":
        del_rect()
        y1 -= 10
    elif event.char == "s":
        del_rect()
        y1 += 10
    # draw_rect()
    draw_rect()


root.bind("<Key>", move)

root.mainloop()

In the following video you can see the game in action.

Moving object on screen: Python, tkinter, canvas, create_rectangle, canvas.delete

In this video there is the moving object made with the previous code.

Tkinter test for students

Tkinter articles

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.