简体   繁体   English

Pygame,屏幕仅在退出 pygame 窗口时更新?

[英]Pygame, screen only updates when exiting pygame window?

I'm fairly new to pygame and i needed some help because my code is not working properly.我对 pygame 相当陌生,我需要一些帮助,因为我的代码无法正常工作。

Okay so here's the problem: I want the screen to turn white when i run it but it remains black, however when i press the exit, it turns white for about a second and then closes.好的,问题来了:我希望在运行它时屏幕变白,但它仍然是黑色的,但是当我按下退出时,它会变白约一秒钟然后关闭。

This also happens when i put a picture (like the player.png) it appears for about a second before exiting.当我放一张图片(如 player.png)时,它也会在退出前出现大约一秒钟。 I don't know what i'm doing wrong,我不知道我做错了什么

please help fix the code and explain why it is happening?请帮助修复代码并解释为什么会发生?

here is the code:这是代码:

import pygame

pygame.init()

screen = pygame.display.set_mode((640,480))
image = pygame.image.load('player.png')
gameExit = False
gameLoop = True

pygame.display.update()
white = (255,255,255)

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

    for event in pygame.event.get():
        screen.fill(white)







pygame.display.update()




pygame.quit()
quit()

PS.附注。 I don't get any errors我没有收到任何错误

Python is indentation sensitive. Python 对缩进敏感。 In your code, you call pygame.display.update() only once your main loop ends.在您的代码中,您只在主循环结束时调用pygame.display.update()

Also, you only paint the background white in the case there's an event in the event queue between the two for loops, and then you fill the background for every event in the queue.此外,如果在两个for循环之间的事件队列中有一个事件,则只将背景涂成白色,然后为队列中的每个事件填充背景。

Note that this could also lead to a situation in which your QUIT event is "swallowed" by the second loop.请注意,这也可能导致您的QUIT事件被第二个循环“吞噬”的情况。


So this所以这

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

    for event in pygame.event.get():
        screen.fill(white)

pygame.display.update()

should be应该

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

    screen.fill(white)

    pygame.display.update()

Ok, so I agree with Sloth, but instead of doing all the screen updating and filling and blitting at the end, making the script less readable, you should make like an animate function that runs at the end of the while loop each time, and put the blitting and screen updating stuff in that function.好的,所以我同意 Sloth,但不是在最后进行所有屏幕更新、填充和 blitting,从而降低脚本的可读性,您应该像每次在 while 循环结束时运行的animate函数一样,并且将 blitting 和屏幕更新内容放在该函数中。 Sorry for the run-on sentence.对不起,连贯的句子。

Oh and you don't need your GameLoop variable.哦,你不需要你的GameLoop变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM