简体   繁体   English

在Tkinter中删除画布小部件

[英]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()

Right now I am trying to make a game where you have to dodge rectangles, which are pipes. 现在,我正在尝试制作一个游戏,您必须躲避矩形(即管道)。 It is basically Flappy Bird, but on Tkinter. 它基本上是飞扬的鸟,但在Tkinter。 In this code I am trying to generate pipes and move them, but the pipes I have drawn before do not leave and they just stay there. 在这段代码中,我试图生成管道并移动它们,但是我之前绘制的管道不会离开,而只会停留在那儿。 This means that when the pipe moves, the position it was just in doesnt change and that shape stays there. 这意味着,当管道移动时,管道的原位置不变,并且形状保持在那里。 Is there any way to delete past shapes, or another way to move them? 有什么方法可以删除过去的形状,或以其他方式移动它们?

canvas.create_rectangle(self.pipe_pos, fill = "green") returns an ID. canvas.create_rectangle(self.pipe_pos, fill = "green")返回一个ID。

You can use this ID to put it into methods like 您可以使用此ID将其放入类似的方法中

canvas.coords
canvas.delete
canvas.itemconfigure
canvas.scale
canvas.type
...

Have a look at help(canvas) . 看一下help(canvas)

The canvas is not a framebuffer on which you paint stuff for one frame. 画布不是可在其上绘制一帧内容的帧缓冲区。 The painted stuff does not go away and you can move it and change all the parameters you can use when creating. 绘画的东西不会消失,您可以移动它并更改在创建时可以使用的所有参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM