为什么我的 pygame 窗口几秒钟后没有响应?

问题描述 投票:0回答:1

这是我的代码,当我运行它时它只是冻结,我不知道为什么

import pygame
import sys



pygame.init()
(5, 0)
#game window
screen_width = 800
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('battle')


#load images
#background image
background_img = pygame.image.load(r"C:\Users\olive\AppData\Local\Programs\Python\Python312\Lib\idlelib\created games.package\rpg\img\setting\Background.png").convert_alpha()

#function for drawing background
def draw_bg():
    screen.blit(background_img,(0,0))


run = True

while run:
    #draw background
    draw_bg()

    
for event in pygame.event.get():
 if event.type == pygame.QUIT:
  run = False

            
  pygame.display.update()
          
pygame.quit()


我不知道该尝试什么,我使用最新版本的 python 和最新版本的 pygame

python pygame
1个回答
0
投票

这是一个简单的缩进错误。在Python中,当编写while循环时,当代码有缩进时,while循环将运行其下的所有代码,例如这将起作用:

while run:
    dosomething()

但这不会:

while run:
dosomething()

并且in while 循环运行后没有代码。如果您想重复更新和监听任何事件,您需要将其放入内部 while 循环,如下所示:

import pygame
import sys

pygame.init()

#(5, 0)
#game window

screen_width = 800
screen_height = 400

screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('battle')

#load images
#background image
background_img = pygame.image.load(r"C:\Users\olive\AppData\Local\Programs\Python\Python312\Lib\idlelib\created games.package\rpg\img\setting\Background.png").convert_alpha()

#function for drawing background
def draw_bg():
    screen.blit(background_img,(0,0))

run = True

while run:

    #draw background
    draw_bg()
    
    #while running check for events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            
    #while running update screen
    pygame.display.update()
          
pygame.quit()

祝您编写其余代码愉快!

© www.soinside.com 2019 - 2024. All rights reserved.