pygame.error:视频系统未初始化
- 2025-03-21 09:06:00
- admin 原创
- 29
问题描述:
每当我尝试执行我的pygame
代码时都会出现此错误:pygame.error: video system not initialized
from sys import exit
import pygame
from pygame.locals import *
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
screen = screen_width, screen_height = 600, 400
clock = pygame.time.Clock()
pygame.display.set_caption("Physics")
def game_loop():
fps_cap = 120
running = True
while running:
clock.tick(fps_cap)
for event in pygame.event.get(): # error is here
if event.type == pygame.QUIT:
running = False
screen.fill(white)
pygame.display.flip()
pygame.quit()
exit()
game_loop()
#!/usr/bin/env python
解决方案 1:
您还没有给pygame.init()
任何地方打过电话。
请参阅基本入门教程,或具体的导入和初始化教程,其中解释了:
在对 pygame 进行更多操作之前,你需要初始化它。最常见的方法是进行一次调用。
pygame.init()
这将尝试为您初始化所有 pygame 模块。并非所有 pygame 模块都需要初始化,但这会自动初始化需要初始化的模块。您也可以轻松地手动初始化每个 pygame 模块。例如,仅初始化您刚刚调用的字体模块。
在您的特定情况下,它可能pygame.display
会抱怨您调用了 itsset_caption
或 itsflip
而没有先调用 its init
。但实际上,正如教程所说,最好只将init
所有内容放在顶部,而不是试图弄清楚什么时候需要初始化什么。
解决方案 2:
将代码更改为此,可避免该错误。运行时:clock.tick(fps_cap)
for event in pygame.event.get(): #error is here
if event.type == pygame.QUIT:
running = False
pygame.quit()
if running:
screen.fill(white)
pygame.display.flip()
解决方案 3:
pygame.quit()
对于我来说,这是一个问题,因为我最后没有跳出循环。
解决方案 4:
我对你的代码做了一些修改:
import os
import sys
import math
import pygame
import pygame.mixer
from pygame.locals import *
pygame.init()
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
screen = pygame.display.set_mode((600, 400))
clock = pygame.time.Clock()
pygame.display.set_caption("Physics")
while True:
clock.tick(120)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
screen.fill(green)
pygame.display.flip()
解决方案 5:
#这将欺骗系统,使其认为它具有视频访问权限
import os
import sys
os.environ["SDL_VIDEODRIVER"] = "dummy"
解决方案 6:
您收到错误是因为您尝试设置窗口标题(使用set_caption()
)但尚未创建 pygame 窗口,所以您的screen
变量只是一个包含未来窗口大小的元组。
要创建 pygame 窗口,您必须调用pygame.display.set_mode(windowSize)
。
祝你好运 :)
解决方案 7:
如果您
pygame.init()
这样做,则解决了视频系统初始化问题。但您会收到以下错误:
(
AttributeError: tuple object has no attribute 'fill'
) 这。
当你这样做时,这个问题正在解决
screen = pygame.display.set_mode((600, 400))
但不是这样做
screen = screen_width, screen_height = 600, 400
那么整个问题就解决了。
解决方案 8:
你只需添加
exit()
停止运行代码示例:
for event in pygame.event.get(): #error is here
if event.type == pygame.QUIT:
running = False
exit() # Solution
解决方案 9:
如果你在窗口class
中使用,pygame
请不要pygame.init()
在你的中使用class
。请pygame.init()
在下面的库中使用。
解决方案 10:
您必须添加:
pygame.init()
在退出显示之前,您应该停止 while 循环。
解决方案 11:
您需要使用此命令初始化 pygame
pygame.init
If the problem is not solved then following this step
当您使用测试版时就会出现此问题。
所以我的建议是请使用新的,旧版本(如果现在使用的是 3.8 python,则需要安装 python 3.7)
现在转到 python 终端并安装 pygame (pip install pygame)
现在问题解决了......
扫码咨询,免费领取项目管理大礼包!