关于Pygame运行无响应问题的办法(已解决)

目录

pygame程序运行时需要初始化

在关闭运行页面的时候无响应


pygame程序运行时需要初始化

如下代码运行后无反应:

import sys
import pygame

size = width, height = 600, 400
screen = pygame.display.set_mode(size)
screen.fill('white')
pygame.display.set_caption('此代码运行无响应')

while True:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()      
        
            
    screen.fill('white')
    pygame.display.flip()

应该加上初始化的语句:

pygame.init()

再运行就会解决问题,代码如下:

import sys
import pygame

pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode(size)
screen.fill('white')
pygame.display.set_caption('此代码运行有响应')


while True:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()      
        
            
    screen.fill('white')
    pygame.display.flip()

 可以看见一个白色的空白页面

在关闭运行页面的时候无响应

 如上代码运行后,准备关闭时,又出现了的情况(我的母语是无语。。。)

 原因是少了这行代码:

pygame.quit()

 加上后代码如下所示:

import sys
import pygame

pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode(size)
screen.fill('white')
pygame.display.set_caption('此代码运行有响应')


while True:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit();
            sys.exit()      
        
            
    screen.fill('white')
    pygame.display.flip()

 这时候就可以正常关闭了

注意!!:

pygame.quit() 要在 sys.exit() 的前面运行,即要先关闭pygame的运行

 if event.type == pygame.QUIT:
            pygame.quit();
            sys.exit()      

猜你喜欢

转载自blog.csdn.net/m0_51783792/article/details/124064511