不会传递对象

时间:2017-05-15 21:07:34

标签: python-3.x tkinter

我一直在研究小行星,但我的随机移动小行星功能不会发生。这是代码 -

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移动。我将类播放器作为参考,以显示过去的画布工作。感谢。

1 个答案:

答案 0 :(得分:1)

Asteriod()的构造函数调用作为参数传递到canvas。但构造函数不会创建名为canvas的属性,换句话说,没有赋值

self.canvas = canvas

但方法move()调用self.canvas.move(),这意味着self.canvas必须存在。它没有,这就是你得到消息'Asteroid' object has no attribute 'canvas'

的原因