python - Pygame:窗口没有响应

标签 python pygame

我是一名业余编码员,最近开始使用 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)

关于python - Pygame:窗口没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48266456/

相关文章:

python - 将对象注入(inject)到类实例中

pygame.mouse.get_pos和Rect.collidepoint的Python表面真实位置坐标

python - Django - 将参数传递给 CBV 装饰器的正确方法?

python - 有什么东西可以影响 time.sleep() 比我需要的更早发生吗?

python - Python/pygame 中的语法错误

python - Pygame 平移表面给定量

python - Pygame:无法打开文件。同一目录

python - 在 ElementTree/Python 中使用多个属性查找事件

python - 检查名称是否已定义?

python - Pandas 数据框的递归转置