英文:
Error: video system not initialized when using pygame
问题
我每次尝试运行这段代码时都遇到错误:
import pygame
pygame.init()
print(pygame.display.Info())
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game")
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.quit:
run = False
pygame.quit()
if __name__ == "__main__":
main()
我尝试添加了 pygame.init()
但没有帮助。
英文:
I keep having the error whenever I try to run this code:
import pygame
pygame.init()
print(pygame.display.Info())
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game")
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.quit:
run = False
pygame.quit()
if __name__ == "__main__":
main()
I've tried adding pygame.init()
but it didn't help.
答案1
得分: 0
这里有一些问题。错误的直接原因是你对pygame.quit()
的调用不在main
函数内部,所以它在程序启动时立即被调用。你需要修复这个问题:
import pygame
pygame.init()
print(pygame.display.Info())
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game")
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if __name__ == "__main__":
main()
这将使你的程序能够运行...但它永远不会退出。你正在比较event.type == pygame.quit
,但pygame.quit
是一个函数;这个比较将始终为False
。你需要将其与pygame.QUIT
进行比较,这是一个整数值,将与event.type
匹配,如预期的那样:
import pygame
pygame.init()
print(pygame.display.Info())
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game")
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if __name__ == "__main__":
main()
英文:
You have a couple of problems here. The immediate cause of the error is that your call to pygame.quit()
isn't inside the main
function, so it gets called immediately when the program starts. You need to fix that:
import pygame
pygame.init()
print(pygame.display.Info())
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game")
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.quit:
run = False
pygame.quit()
if __name__ == "__main__":
main()
This will allow your program to run...but it's never going to quit. You're comparing event.type == pygame.quit
, but pygame.quit
is a function; this comparison will always be False
. You need to compare it to pygame.QUIT
, which is an integer value that will match event.type
as expected:
import pygame
pygame.init()
print(pygame.display.Info())
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game")
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if __name__ == "__main__":
main()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论