【问题标题】:Python pygame window keeps crashingPython pygame窗口不断崩溃
【发布时间】:2013-12-09 06:27:54
【问题描述】:

每当我运行我的代码时,出现的 Python 窗口都不会响应。
我的代码有问题还是我必须重新安装 pygame 和 python?
我得到一个黑色的 pygame 窗口,然后它变成白色并说没有响应?
我也是新手,所以请尽可能简单。我试图到处寻找答案,但无法以我能理解的方式得到答案。
请帮帮我。谢谢:)

1 - 导入库

import pygame
from pygame.locals import *

2 - 初始化游戏

pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))

3 - 加载图片

player = pygame.images.load("resources/images/dude.png")

4 - 继续循环

while 1:
    # 5 - clear the screen before drawing it again
    screen.fill(0)
    # 6 - draw the screen elements
    screen.blit(player, (100,100))
    # 7 - update the screen
    pygame.display.flip()
    # 8 - loop through the events
    for event in pygame.event.get():
        # check if the event is the X button
        if event.type==pygame.QUIT:
            # if it is quit the game
            pygame.quit()
            exit(0)

【问题讨论】:

  • 尝试放入 print 语句来找出它崩溃的地方,一个好的开始是在 while 循环之前放置一个,看看它是否在它停止工作之前到达那里。
  • 如果if event.type--pygame.QUIT: 实际上在您的代码中,那么您确实有问题。您想使用== 而不是--
  • 我把它从 -- 改成了 == 但还是不行。我该怎么办?
  • 它会给你一个错误信息吗?
  • 顺便说一句:应该是 pygame.image.load 代替 pygame.images.load - image 没有 s

标签: python crash pygame


【解决方案1】:

不要导入pygame.locals。这实际上是不必要的,因为您已经在导入 pygame

另外,正如@furas 所说,应该是:

player = pygame.image.load("resources/images/dude.png")

不是:

player = pygame.images.load("resources/images/dude.png")

这将清除您代码中的一些问题。

【讨论】:

    【解决方案2】:

    根据我的个人经验,如果您从 IDLE 运行 pygame 代码,它通常根本没有响应。尝试将您的项目保存为 .py 文件,然后使用 python.exe 运行它。它总是对我有用。 正如furas所说,使用

    player = pygame.image.load("resources/images/dude.png")
    

    而不是

    player = pygame.images.load("resources/images/dude.png")
    

    【讨论】:

    • 最佳答案!您必须编写 pygame 代码并将其保存到 .py 文件中。然后它工作。它使用 jupyter notebook 一直冻结,使用 python shell 时也冻结。运行 .py 文件就可以了!
    【解决方案3】:

    用这个替换那个for循环

     while not done:
       for event in pygame.event.get():
         if event.type == pygame.QUIT:
           done = True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多