2

私は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()

それは長方形を作成するためのものですが、私の質問は、作成した長方形にどのようにアクセスすればよいですか? のようなものを試しています。

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

しかし、それを使用して移動しようとすると

r1.move(10,10)

エラーが発生する

r1.move(10,10) AttributeError: 'NoneType' オブジェクトに属性 'move' がありません

どのようにアクセスすればよいですか?ありがとう-

4

2 に答える 2

2

Python 関数のデフォルトの戻り値はNoneです。None関数に return ステートメントがないため、 attribute を持たないものを返しますmove()

Python ドキュメントから

実際、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
于 2013-07-21T14:51:27.837 に答える
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.

次に、四角形を作成してメソッドを使用することもできます-

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

それはうまくいくはずです

于 2013-07-21T14:52:29.957 に答える