0

试图学习如何使用 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()
4

2 回答 2

2

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

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因为您的函数从不返回值。

于 2013-07-27T19:52:45.097 回答
2

你还没有定义一个 Ball 类,你已经定义了一个名为 Ball 的函数。

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

class Ball(Widget):

(假设 Ball 像 Bubble 一样从 Widget 继承)。

于 2013-07-27T19:52:54.333 回答