【问题标题】:Remove canvas widgets in Tkinter在 Tkinter 中删除画布小部件
【发布时间】:2014-04-15 04:37:37
【问题描述】:
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 上。在这段代码中,我试图生成管道并移动它们,但是我之前绘制的管道并没有离开,它们只是留在那里。这意味着当管道移动时,它所在的位置不会改变,并且形状会保持在那里。有什么方法可以删除过去的形状,或者有其他方法可以移动它们吗?

【问题讨论】:

    标签: python canvas tkinter


    【解决方案1】:

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

    您可以使用此 ID 将其放入方法中,例如

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

    看看help(canvas)。

    画布不是一个帧缓冲区,您可以在其上为一帧绘制内容。绘制的东西不会消失,您可以移动它并更改创建时可以使用的所有参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2019-08-07
      • 2015-02-17
      相关资源
      最近更新 更多