【问题标题】:Python Crash Course: "pygame.error: video system not initialized" [duplicate]Python速成课程:“pygame.error:视频系统未初始化” [重复]
【发布时间】:2018-03-08 14:30:55
【问题描述】:

我正在尝试做 Python 速成课程书籍中的一个项目:Alien Invasion 第 12 章。我刚开始,由于某种原因,错误:pygame.error: video system not initialized 不断弹出。我很确定我正确地遵循了指示,所以我不知道我可能做错了什么......?

import sys

import pygame

from settings import Settings

def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Alien Invasion')

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            screen.fill(ai_settings.bg_color)
            pygame.quit()
            sys.exit()

    pygame.display.flip()
run_game()

【问题讨论】:

  • 尝试在while 块中添加一级缩进。
  • run_game 永远不会被调用,因为在您的情况下,退出无限循环的唯一方法是 sys.exit,它会杀死脚本。
  • 我也是这么想的,但书上是这么说的。我尝试移动或摆脱 'sys.exit,但仍然收到错误消息。我也试过删除run_game,但显然游戏没有运行

标签: python pygame


【解决方案1】:

发生错误是因为在您使用pygame.display.set_mode 初始化显示之前调用了pygame.event.get

在 Python 中正确缩进代码非常重要。您的程序应该很可能与此版本相似:

import sys

import pygame

from settings import Settings

def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Alien Invasion')
    # This block should be in the `run_game` function.
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # Fill the screen in the while loop not in the event
        # loop. It makes no sense to fill the screen only when
        # the user quits.
        screen.fill(ai_settings.bg_color)
        pygame.display.flip()

run_game()

【讨论】:

  • 我试过你的代码,但现在我得到了: Traceback(最近一次调用最后一次):AttributeError: 'Settings' object has no attribute 'screen_width' 这是否意味着我的settings.py 文件未连接到原始文件?
  • 这意味着您的 Settings 类没有 screen_width 属性。您是否在 settings.py 文件的其他地方定义了它?
  • 'class Settings(): def _intit_(self): self.screen_width = 800 self.screen_height = 1200 self.bg_color = 230,230,230'
  • 有些错别字:def _intit_(self): 应该是def __init__(self):
  • 'AttributeError: 'Settings' 对象没有属性 'screen_width''
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多