How to delete a form already created in Tkinter canvas?

from Tkinter import *


a = Tk()

canvas = Canvas(a, width = 500, height = 500)
canvas.pack()

canvas.create_rectangle(0,0,100,100)

Now, how do we remove this rectangle that was created ???

Edit:

It was related to the game that I created. This is a simple game where, if the ball hits the block, the block should disappear. But if I did something like this:

class Block:
    def __init__(self,canvas,color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(10,10,110,20,fill=color )
        self.id1 = canvas.create_rectangle(115,10,215,20,fill=color)
        self.id2 = canvas.create_rectangle(220,10,320,20,fill=color)
        self.id3 = canvas.create_rectangle(325,10,425,20,fill=color)
        self.id4 = canvas.create_rectangle(430,10,530,20,fill=color)
        self.id5 = canvas.create_rectangle(100,150,200,160,fill=color)
        self.id6 = canvas.create_rectangle(350,150,450,160,fill=color)
        self.x = 0

and then:

    def hit_block(self,pos):
        block_pos = self.canvas.coords(self.block.id)
        List = [block_pos]
        for i in List:
            if pos[0] >= i[0] and pos[2] <= i[2]:
                if pos[1] >= i[1] and pos[1] <= i[3]:
                    canvas.delete(block.id)
                    self.score()
                    global a
                    a += 1
                    return True
        return False

This does not work. So could you help me in removing the block when the ball hit him?

+9
source share
2 answers

Assign to a create_rectangle()variable, and then call canvas.delete()for that variable:

from Tkinter import *


a = Tk()

canvas = Canvas(a, width = 500, height = 500)
canvas.pack()

myrect = canvas.create_rectangle(0,0,100,100)
canvas.delete(myrect) #Deletes the rectangle

Window before uninstallation:

Picture before deletion

Window after removal:

Picture after deletion

+14
source

, , if , A.J if.

-1

Source: https://habr.com/ru/post/1540810/


All Articles