在 Tkinter 中删除画布小部件 [英] Remove canvas widgets in Tkinter

查看:42
本文介绍了在 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()

现在我正在尝试制作一个游戏,您必须躲避矩形,即管道.它基本上是 Flappy Bird,但在 Tkinter 上.在这段代码中,我试图生成管道并移动它们,但我之前绘制的管道不会离开,它们只是留在那里.这意味着当管道移动时,它所在的位置不会改变并且形状保持在那里.有没有办法删除过去的形状,或者用其他方式移动它们?

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. 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") 返回一个 ID.

您可以使用此 ID 将其放入诸如

You can use this ID to put it into methods like

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

看看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.

这篇关于在 Tkinter 中删除画布小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆