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

求助:解决pygame.error: video system not initialized报错问题

Pygame报错pygame.error: video system not initialized排查与修复

你的代码触发该错误的核心原因是视频系统被提前关闭后仍调用了依赖视频系统的API,同时代码还存在其他几处语法/逻辑错误,逐一修复如下:

关键错误点分析

  • 错误覆盖屏幕对象:scr = pygame.display.set_caption(...),pygame.display.set_caption()返回None,这会把之前用pygame.display.set_mode()创建的屏幕对象覆盖为None,后续绘制操作完全失效。
  • 事件类型判断错误:event.type == pygame.quit()是错误写法,pygame.quit()是关闭Pygame的函数,正确的退出事件常量是pygame.QUIT。
  • 提前关闭视频系统后仍执行后续代码:在处理退出事件时立刻调用pygame.quit(),但循环并未立即终止,后续的all_sprites.update()会调用Button的update方法,其中pygame.mouse.get_pos()依赖已关闭的视频系统,直接触发报错。
  • Button类笔误:self.image.blit(self.text_image, self.text.rect)中的self.text.rect应为self.text_rect。
  • 按钮坐标错误:按钮初始化时y参数误用了Screen_width,应该是Screen_height。
  • 绘制逻辑缩进错误:all_sprites.update()、all_sprites.draw(scr)、pygame.display.flip()应该放在事件循环的外层,而非for event in pygame.event.get()的循环内部,否则会导致每处理一个事件就重复绘制,且退出事件后仍执行绘制。

修复后的完整代码

import pygame

pygame.init()

Black = (0, 0, 0)
Gray = (150, 150, 150)
White = (255, 255, 255)
Screen_width = 640
Screen_height = 480

class Button(pygame.sprite.Sprite):
    def __init__(self, text, x, y, width, height):
        super().__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(Black)

        self.font = pygame.font.Font(None, 20)
        self.text_image = self.font.render(text, True, White)

        self.text_rect = self.text_image.get_rect(center=(width//2, height//2))
        self.image.blit(self.text_image, self.text_rect)

        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.centery = y

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(mouse_pos):
            self.image.fill(Black)
        else:
            self.image.fill(Gray)

        self.image.blit(self.text_image, self.text_rect)

# 创建屏幕对象,不要覆盖
scr = pygame.display.set_mode((Screen_width, Screen_height))
pygame.display.set_caption('Заголовок окошка игры )')
my_button = Button('Это моя кнопка', Screen_width / 2, Screen_height / 2, 100, 100)

all_sprites = pygame.sprite.Group()
all_sprites.add(my_button)

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if my_button.rect.collidepoint(mouse_pos):
                print('Кнопка нажата!')
    
    # 绘制逻辑放在事件循环外层
    all_sprites.update()
    scr.fill(Gray)  # 每次绘制前填充背景,避免残影
    all_sprites.draw(scr)
    pygame.display.flip()

# 循环结束后再关闭Pygame
pygame.quit()
exit()

内容的提问来源于stack exchange,提问作者Tedrey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:39:59