我一直在研究小行星,但我的随机移动小行星功能不会发生。这是代码 -
class Player():
def __init__(self, canvas):
self.shape = canvas.create_rectangle(910, 540, 960, 590, outline = "blue", fill= "white")
self.pos = canvas.coords(self.shape)
self.xspeed = 0
self.yspeed = 0
def move(self, canvas):
canvas.move(self.shape, self.xspeed, self.yspeed)
self.pos = canvas.coords(self.shape)
class Asteroid():
def __init__(self, canvas):
self.One = canvas.create_oval(0,0, 50, 50, fill="grey")
self.speedx = (10)
self.speedy = (10)
def move(self, canvas):
while True:
self.canvas.move(self.One, self.speedx, self.speedy)
self.canvas.after(20)
self.canvas.update()
def game():
#create window and canvas
parent = Tk()
canvas = Canvas(parent, width = 1920, height = 1080,
background="black")
parent.title("Asteroids")
canvas.pack()
#create player
player = Player(canvas)
enemyOne = Asteroid(canvas)
enemyOne.move(canvas)
我收到错误消息 -
AttributeError: 'Asteroid' object has no attribute 'canvas'
因此对象画布不会传递给Asteroids并且def移动。我将类播放器作为参考,以显示过去的画布工作。感谢。
答案 0 :(得分:1)
Asteriod()
的构造函数调用作为参数传递到canvas
。但构造函数不会创建名为canvas
的属性,换句话说,没有赋值
self.canvas = canvas
但方法move()
调用self.canvas.move()
,这意味着self.canvas
必须存在。它没有,这就是你得到消息'Asteroid' object has no attribute 'canvas'
。