You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame中TypeError: 'NoneType'对象不可迭代错误求助

Fixing TypeError: 'NoneType' object is not iterable in Your Pygame Code

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:53:31