我们如何删除已在Tkinter画布中创建的形状?

时间:2014-05-16 00:53:01

标签: python tkinter

from Tkinter import *


a = Tk()

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

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

现在我们如何删除已创建的矩形???

编辑:

这是关于我正在创建的游戏。这是一个简单的游戏,如果球击中阻挡,阻挡应该消失。但如果我做了这样的事情:

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

然后:

    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

它不起作用。那么当球击中它时你能帮我删除阻挡吗?

2 个答案:

答案 0 :(得分:13)

create_rectangle()分配给变量,然后在该变量上调用canvas.delete()

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

删除前的窗口:

Picture before deletion

删除后的窗口:

Picture after deletion

答案 1 :(得分:-1)

基本上他说的只是为坐标添加一些if语句,并插入A.J作为if语句的结果输​​入的内容。