[英]Pygame: window not responding
我是ameatur编码员,最近刚开始使用pygame,并且一直在编码一些示例,而我刚遇到一个在执行时无法正确加载的示例。 我敢肯定我写的正确,但是我不知道为什么它不能运行。 我正在运行python 3.6和Pygame 1.9.3。*
*我知道pygame版本是1.9,但我不知道最后一位。
这是代码:
# This just imports all the Pygame modules
import pygame
# This MUST BE the first thing you put into a program!
pygame.init()
# This tells pygame to open a windo 640 pixels by 480
screen = pygame.display.set_mode((640, 480))
# This is called a while loop
# This is the simplest form of an event loop
# This line procceses the window: Such as telling it to close when the user hits the Escape Key
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
# Y = DOWN
class Game(object):
def main(self, screen):
image = pygame.image.load('player.png')
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
screen.fill((200, 200, 200))
screen.blit(image, (320, 240))
pygame.display.flip()
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((640, 480))
Game().main(screen)
我已经修改了您的代码,因此它现在可以运行。 我检测到的主要问题是,您在运行代码时并不完全了解代码在做什么。
已解决的问题:
删除了无意义的while循环和pygame初始化,这些初始化无论如何在程序执行开始时进行。
缩进if __name__ == "__main__":
分支。 这个分支从来都不是课程的一部分 。 在一个类中,您有方法和变量。 就是这样 。
除了这些问题之外,代码还可以,但是请确保在继续之前了解它的作用。
希望这个答案对您有所帮助,如果您还有其他疑问,请随时在下面发表评论!
修改后的代码示例:
# This just imports all the Pygame modules
import pygame
class Game(object):
def main(self, screen):
image = pygame.image.load('player.png')
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
screen.fill((200, 200, 200))
screen.blit(image, (320, 240))
pygame.display.flip()
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((640, 480))
Game().main(screen)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.