Python访问变量

时间:2013-07-21 14:45:53

标签: python pygame

我是python的新手,我正在尝试使用pygame,但不知道我该怎么做..

def addRect(x, y, width, height, color, surface):
    rect = pygame.Rect(x, y, width, height)
    pygame.draw.rect(surface, color, rect)
    pygame.display.flip()

这是创建矩形,但我的问题是我应该如何访问我创建的ractangles?我正在尝试类似的东西。

r1 = addRect(20, 40, 200, 200, (61, 61, 61), screen)

但是当我尝试使用

移动它时
r1.move(10,10)

我收到错误

  

r1.move(10,10)   AttributeError:'NoneType'对象没有属性'move'

我该如何访问它?感谢 -

2 个答案:

答案 0 :(得分:2)

Python函数的默认返回值为None。由于您的函数中没有return语句,因此返回None,其中没有属性move()

来自The Python Docs

  

实际上,即使没有return语句的函数也会返回一个值,   虽然是一个相当无聊的人。该值称为None(它是内置的   名称)。

>>> def testFunc(num):
        num += 2

>>> print testFunc(4)
None

您需要添加return语句才能返回rect变量。

def addRect(x, y, width, height, color, surface):
    rect = pygame.Rect(x, y, width, height)
    pygame.draw.rect(surface, color, rect)
    pygame.display.flip()
    return rect

答案 1 :(得分:2)

我不太了解PyGame,但你可以修改addRect -

def addRect(x, y, width, height, color, surface):
    rect = pygame.Rect(x, y, width, height)
    pygame.draw.rect(surface, color, rect)
    pygame.display.flip()
    return rect # Added this line. Returns the rect object for future use.

然后你也可以制作rects并使用方法 -

rect1 = addRect(20, 40, 200, 200, (61, 61, 61), screen)
rect1.move(10,10)

那应该有用

相关问题