Python画布不会绘制多条线

时间:2019-07-27 03:54:01

标签: python python-3.x canvas tkinter tkinter-canvas

我正在创建2D游戏,当我尝试添加多个墙时,它们不会出现在画布上。

import tkinter

root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack()

class wall:
  point1 = []
  point2 = []
  def __init__(self, canvas, x1, y1, x2, y2):
    self.canvas = canvas
    self.point1.append(x1)
    self.point1.append(y1)
    self.point2.append(x2)
    self.point2.append(y2)
  def draw(self):
    self.canvas.create_line(self.point1[0], self.point1[1], self.point2[0], self.point2[1], width = 2)

walls = []
walls.append(wall(canvas, 90, 90, 100, 200))
walls.append(wall(canvas, 90, 90, 300, 100))

def update():
    for wall in walls:
        wall.draw()
    root.after(int(1000/60), update)
root.after(int(1000/60), update)
root.mainloop()

如果我手动添加它们,它们都会同时绘制。

canvas.create_line(90, 90, 100, 200, width = 2)
canvas.create_line(90, 90, 300, 100, width = 2)

2 个答案:

答案 0 :(得分:2)

考虑班级wall的这一部分:

class wall:
    point1 = []
    point2 = []
    ...

列表point1point2被定义为类属性而不是实例属性。因此,当您添加新坐标时,以前的坐标仍然存在。

要解决此问题,只需设置pointpoint2实例属性即可:

class wall:

    def __init__(self, canvas, x1, y1, x2, y2):
        self.point1 = []
        self.point2 = []
        ...

或直接使用参数:

class wall:
    def __init__(self, canvas, x1, y1, x2, y2):
        self.canvas = canvas
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
    def draw(self):
       self.canvas.create_line(self.x1, self.y1, self.x2, self.y2, width = 2)

答案 1 :(得分:-2)

class wall:
  def __init__(self, canvas, x1, y1, x2, y2):
    self.canvas = canvas
    self.x1 = x1
    self.y1 = y1
    self.x2 = x2
    self.y2 = y2
  def draw(self):
    self.canvas.create_line(self.x1, self.y1, self.x2, self.y2, width = 2)