[英]Remove canvas widgets in Tkinter
from Tkinter import *
import random
root = Tk()
width = 700
height = 600
canvas = Canvas(root, width = width, height = height, bg = "light blue")
canvas.pack()
pipes = []
class NewPipe:
def __init__(self, pipe_pos, pipe_hole):
self.pipe_pos = list(pipe_pos)
def update(self):
self.pipe_pos[0] -= 3
self.pipe_pos[2] -= 3
def draw(self):
canvas.create_rectangle(self.pipe_pos, fill = "green")
def get_pos(self):
return self.pipe_pos
def generate_pipe():
pipe_hole = random.randrange(0, height)
pipe_pos = [width - 100, 0, width, pipe_hole]
pipes.append(NewPipe(pipe_pos, pipe_hole))
draw_items()
canvas.after(2000, generate_pipe)
def draw_items():
for pipe in pipes:
if pipe.get_pos()[2] <= 0 - 5:
pipes.remove(pipe)
else:
pipe.draw()
pipe.update()
canvas.after(100, draw_items)
def jump(press):
pass
canvas.bind("<Button-1>", jump)
canvas.after(2000, generate_pipe)
draw_items()
mainloop()
现在,我正在尝试制作一个游戏,您必须躲避矩形(即管道)。 它基本上是飞扬的鸟,但在Tkinter。 在这段代码中,我试图生成管道并移动它们,但是我之前绘制的管道不会离开,而只会停留在那儿。 这意味着,当管道移动时,管道的原位置不变,并且形状保持在那里。 有什么方法可以删除过去的形状,或以其他方式移动它们?
canvas.create_rectangle(self.pipe_pos, fill = "green")
返回一个ID。
您可以使用此ID将其放入类似的方法中
canvas.coords
canvas.delete
canvas.itemconfigure
canvas.scale
canvas.type
...
看一下help(canvas)
。
画布不是可在其上绘制一帧内容的帧缓冲区。 绘画的东西不会消失,您可以移动它并更改在创建时可以使用的所有参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.