Pygame中TypeError: 'NoneType'对象不可迭代错误求助
Hey there, let's break down what's causing this error and how to fix it quickly.
The Root Cause
Your TypeError happens because the text_objects function isn't returning anything—by default, Python functions return None if there's no explicit return statement. When screen_message tries to unpack the result of text_objects(msg, color) into textSurf, textRect, it's trying to iterate over None, which throws that error.
Looking at your code snippet:
def text_objects(text, color, size="small"): smallfont = pygame.font.SysFont("comicsansms", 26) if size == "small": textSurface = smallfont.render(text, True, color)
Even when size == "small" is true, you create textSurface but never send it back to the caller. For any other size value, the function does nothing at all—still returning None.
The Fix
Update the text_objects function to return the rendered text surface and its rectangle (which you'll need for positioning). Here's the corrected version:
def text_objects(text, color, size="small"): if size == "small": font = pygame.font.SysFont("comicsansms", 26) # Optional: Add handling for other sizes if you need them elif size == "large": font = pygame.font.SysFont("comicsansms", 50) else: # Fallback to small font if an unknown size is passed font = pygame.font.SysFont("comicsansms", 26) textSurface = font.render(text, True, color) # Return both the surface and its rect (for positioning) return textSurface, textSurface.get_rect()
Why This Works
Now when screen_message calls text_objects(msg, color), it gets a tuple containing two valid objects (the text surface and its rectangle) instead of None. The line textSurf, textRect = text_objects(msg, color) can properly unpack these values, and your code will proceed to center and draw the message as expected.
Just drop this corrected function into your code, and the error from line 74 of game_intro should be gone!
内容的提问来源于stack exchange,提问作者CuteCats

