質問

Consider:

from Tkinter import *


a = Tk()

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

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

How do we delete this rectangle that's been created?

This is in reference to a game I am creating. It's a simple game where if the ball hits the block, the block should disappear. But if I do 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

It doesn't work. How can I delete the block when the ball hits it?

役に立ちましたか?

解決

Assign the create_rectangle() to a variable, and then call canvas.delete() on 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 deletion:

Picture before deletion

Window after deletion:

Picture after deletion

他のヒント

In my opinion better option is add a Option tags= to function create_rectangle() and u can avoid creating new variables.

from Tkinter import *
a = Tk()
canvas = Canvas(a, width = 500, height = 500)
canvas.pack()

canvas.create_rectangle(0,0,100,100, tags="square")
canvas.delete("square") #Deletes the rectangle wchich have tags option named "square"

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

Btw. it's a problem when u "delete" an object from myrect to "create" them again in the same variable.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top