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

Python报错AttributeError:'Settings'对象无'screen'属性,求协助

解决AttributeError: 'Settings' 对象没有 'screen' 属性的问题

嗨,我看了你的代码和报错,问题其实很简单——就是个拼写错误!

错误根源

你在初始化pygame窗口的时候写了这么一行:

screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen.height))

这里的ai_settings.screen.height完全是错的!你的Settings类里根本没有screen这个属性,你定义的是screen_height啊!

修正后的完整代码

先保持你的Settings类不变:

class Settings():
    def __init__(self):
        self.screen_width=1200
        self.screen_height=800
        self.bg_color=(230,230,230)

然后修改run_game函数里的错误行,顺便补充你没写完的部分:

import sys
import pygame
from settings import Settings

def run_game():
    pygame.init()
    ai_settings=Settings()
    # 修正拼写错误:screen.height → screen_height
    screen=pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Inwazja obcych")
    
    while True:
        # 填充背景色
        screen.fill(ai_settings.bg_color)
        # 刷新屏幕
        pygame.display.flip()
        
        # 处理退出事件(避免程序卡死)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

run_game()

为啥会触发这个错误?

AttributeError的本质就是:你试图访问一个对象根本不存在的属性。你的ai_settings是Settings类的实例,里面只有screen_width、screen_height和bg_color三个属性,没有screen这个子对象,自然也就找不到screen.height了。

这种拼写小错误很常见,下次写代码时多留意变量名的对应关系就好啦!

内容的提问来源于stack exchange,提问作者Łukasz Lubiński

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:43:06