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
相关产品推荐
相关产品推荐

