在python中没有正确初始化类

时间:2013-07-27 19:41:46

标签: python kivy

试着学习如何使用Kivy(之前从未编写过除学校作业之外的其他任何东西),而且我遇到了一些麻烦。

我的代码如下所示。

问题在于我的Ball类,当应用程序启动时BubblePop.SetupLevel()被调用,并且球应该被Ball类的实例填充。但不知怎的,它不起作用。因此,当BobblePop.update()被调用时,我会在ball.draw()

上收到错误消息
AttributeError: 'NoneType' object has no attribute 'draw'


from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
    ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.graphics import Color, Ellipse
from random import random, randint
from kivy.core import window
#balls are what bounce around the screen. They turn into bubbles upon 
#colliding with a bubble.

def Ball(width,height):
    def __init__(self,width,height):
        self.x = randint(0,width)
        self.y = randint(0,height)
        self.colorRGB = [0,0,0]
        self.velX = 0
        self.velY = 0
        self.ball_size = 20

    def draw(self):
        Ellipse(pos=(self.x,self.y), size = (self.ball_size,self.ball_size))


class Bubble(Widget):
    pass

class BubblePop(Widget):
    balls = []
    bubbles = []

    def SetupLevel(self,numballs):
        for x in xrange(numballs):
            ball = Ball(self.height,self.width)
            self.balls.append(ball)

    def on_touch_down(self,touch):
        with self.canvas:
            r = random()
            g = random()
            b = random()
            Color(r,g,b)
            d = 80.
            self.bubbles.append([touch.x - d / 2,touch.y - d / 2,[r,g,b]])
            Ellipse(pos=(self.bubbles[-1][0], self.bubbles[-1][1]), size=(d, d))


    def update(self,dt):
        with self.canvas:
            self.canvas.clear()
            for ball in self.balls:
                ball.draw()

class BubbleApp(App):
    def build(self):
        game = BubblePop()
        game.SetupLevel(10)
        Clock.schedule_interval(game.update, 1.0/60.0)
        return game


if __name__ == '__main__':
    BubbleApp().run()

2 个答案:

答案 0 :(得分:2)

你的球“课”看起来很奇怪。你定义它的方式,它不是一个类而是一个函数。

def Ball(width,height):
    def __init__(self,width,height):
        self.x = randint(0,width)
        self.y = randint(0,height)
        self.colorRGB = [0,0,0]
        self.velX = 0
        self.velY = 0
        self.ball_size = 20

我觉得你需要像

这样的东西
class Ball():
    def __init__(self, width, height):
        ...

现在,无论何时拨打b = Ball(...),b都将为None,因为您的功能永远不会返回值。

答案 1 :(得分:2)

您尚未定义Ball类,您已定义了一个名为Ball的函数。

代码本身的第一行应该是:

class Ball(Widget):

(假设Ball继承自Widget,就像Bubble一样)。