[英]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.