Python 我们如何删除已经在 Tkinter 画布中创建的形状?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23690993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do we delete a shape thats already been created in Tkinter canvas?
提问by Avinash12388
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 delete this rectangle that's been created???
现在我们如何删除这个已经创建的矩形???
Edit:
编辑:
This was in reference to a game I was creating. It's 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
It doesn't work. So could you help me in deleting the block when the ball hits it?
它不起作用。那么你能帮我在球击中它时删除它吗?
采纳答案by A.J. Uppal
Assign the create_rectangle()
to a variable, and then call canvas.delete()
on that variable:
将 分配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
Window before deletion:
删除前的窗口:
Window after deletion:
删除后的窗口: