我想创建pygame窗口,但它在VS代码中一直说“视频系统未初始化”

2024-10-02 20:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是VisualDestAudio,但如果使用python IDLE运行,它会运行

import pygame, sys

def run_game():
    
    pygame.init()
    screen = pygame.display.set_mode((1200,800))
    pygame.display.set_caption("Space Invasion")


while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        
    
    pygame.display.flip()

run_game()

Tags: runimporteventgameinitmodedefdisplay
1条回答
网友
1楼 · 发布于 2024-10-02 20:29:45

在进入循环之前,需要首先使用pygame.init()进行初始化。另外,我将sys.exit()替换为pygame.quit(),因为sys.exit()会导致程序在试图关闭程序时不响应

import pygame, sys

def run_game():
    pygame.init()
    screen = pygame.display.set_mode((1200,800))
    pygame.display.set_caption("Space Invasion")


run_game()
while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        
    
    pygame.display.flip()

或者,您可以将循环放在run_game()函数中,就像import random建议的那样

import pygame, sys

def run_game():
    pygame.init()
    screen = pygame.display.set_mode((1200,800))
    pygame.display.set_caption("Space Invasion")

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
        
    
        pygame.display.flip()

run_game() # Run the game

相关问题 更多 >