mport sys import pygame class AlienInvasion: def int(self): pygame.init() self.screen = pygame.display.set_mode((1200,800)) pygame.display.set_caption(“Alien Invasion”)
def run_game(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pygame.display.flip()
if name == ‘main’: pygame.init() ai = AlienInvasion() ai.run_game()
D:\zuojunyun\alien_invasion\venv\Scripts\python.exe D:\zuojunyun\alien_invasion\alien_invasion.py pygame 2.5.2 (SDL 2.28.3, Python 3.11.2) Hello from the pygame community. https://www.pygame.org/contribute.html Traceback (most recent call last): File “D:\zuojunyun\alien_invasion\alien_invasion.py”, line 19, in ai.run_game() File “D:\zuojunyun\alien_invasion\alien_invasion.py”, line 14, in run_game pygame.display.flip() pygame.error: Display mode not set
进程已结束,退出代码为 1
The error pygame.error: Display mode not set indicates that the Pygame display mode has not been initialized properly. This is likely due to a few issues in your code:
pygame.error: Display mode not set
__init__
AlienInvasion
int
if __name__ == '__main__':
Here’s the corrected version of your code:
import sys import pygame class AlienInvasion: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Alien Invasion") def run_game(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pygame.display.flip() if __name__ == '__main__': ai = AlienInvasion() ai.run_game()
run_game
After making these changes, your Pygame window should initialize correctly and you should no longer encounter the Display mode not set error.
Display mode not set