pythonpgzero

Pygame Zero: TypeError: cannot create weak reference to 'NoneType' object


Hello so I am currently programming a little 2D game. I already have movement etc. figured out. Now I want to add a simple animation by using something I found on here:

def anim_right():
    global counter_right
    imagesright = ["tesbold_right1_x1000.png","tesbold_right2_x1000.png"]
    Tesbold.image = imagesright[counter_right]
    counter_right = (counter_right + 1) % len(imagesright)
    print("anim_right ausgeführt")

I have this for every cardinal direction. This also works fine with the only exception that it is seizure enducing because I call up this function in my update() function. Essentially changing the image every single frame.

I was think about adding a clock.schedule_unique but this seems to not work.

If I add it in the animation function itself like this:

def anim_right():
    global counter_right
    imagesright = ["tesbold_right1_x1000.png","tesbold_right2_x1000.png"]
    Tesbold.image = imagesright[counter_right]
    counter_right = (counter_right + 1) % len(imagesright)
    print("anim_right ausgeführt")
    clock.schedule_unique(anim_right(), 0.5)

I get following error code:

RecursionError: maximum recursion depth exceeded

If I try it in my function that is calling up my anim_right() function like this:

def update():               #Updates per Frame
    global walking
    if walking == True:
        if Tesbold.direction == 0:
            clock.schedule_unique(anim_right(), 0.5)

I get the following Error Code:

TypeError: cannot create weak reference to 'NoneType' object

I have searched both Error Codes and have found nothing usefull for my Case.


Solution

  • You get the error "RecursionError: maximum recursion depth exceeded", because anim_right() is a function call statement.
    The line clock.schedule_unique(anim_right(), 0.5) actually calls the function anim_right and pass the return value to clock.schedule_unique. This leads to an endless recursion.

    You have to pass the function itself (anim_right instead of anim_right()):

    clock.schedule_unique(anim_right(), 0.5)

    clock.schedule_unique(anim_right, 0.5)