2

Im new to python and im trying something with pygame but dont know how should I do this..

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

Thats for creating rectangles but my question is how should I access the ractangles I create ? Im trying something like .

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

But then when I try to move it using

r1.move(10,10)

I get an error

r1.move(10,10) AttributeError: 'NoneType' object has no attribute 'move'

How should I access it ? thanks-

1
  • 1
    You are not returning the rect from the function. Commented Jul 21, 2013 at 14:46

2 Answers 2

2

Python functions have a default return value of None. Since, you don't have a return statement in your function, it returns None which does not have an attribute move().

From The Python Docs

In fact, even functions without a return statement do return a value, albeit a rather boring one. This value is called None (it’s a built-in name).

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

>>> print testFunc(4)
None

You need to add a return statement to return the rect variable.

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
Sign up to request clarification or add additional context in comments.

Comments

2

I don't know much PyGame but you could modify 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.

Then you can make rects and use methods too -

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

That should work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.