gpt4 book ai didi

Python Canvas 不绘制多条线

转载 作者:太空宇宙 更新时间:2023-11-03 20:34:56 25 4
gpt4 key购买 nike

我正在创建 2D 游戏,当我尝试添加多于一堵墙时,它们不会出现在 Canvas 上。

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)

最佳答案

考虑类(class)的这一部分:

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)

关于Python Canvas 不绘制多条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57228999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com