Trying to display a png file in pygame using pygame.display.update, and it shows for less than a second then disappears.

左心房为你撑大大i 提交于 2019-12-20 03:52:06

问题


The image is a playing card. We are using pygame 4.5 community edition and pycharm 2.6.9 because 2.7 does not support pygame (this is a school). Here is the code:

import pygame
pygame.init()
picture=pygame.image.load("cards/S01.png")
pygame.display.set_mode(picture.get_size())
main_surface = pygame.display.get_surface()
main_surface.blit(picture, (0,0))
pygame.display.update()

Why does the window disappear?


回答1:


Try this:

import pygame
pygame.init()
picture=pygame.image.load("cards/S01.png")
pygame.display.set_mode(picture.get_size())
main_surface = pygame.display.get_surface()
main_surface.blit(picture, (0,0))
while True:
   main_surface.blit(picture, (0,0))
   pygame.display.update()

pygame.display.update() updates a frame. There are multiple frames per second depending on what what you draw onto the surface.




回答2:


The problem is, after you update the screen with pygame.display.update(), you do nothing, and your program simply ends. pygame.display.update() does not block.

You need what is usually called a main loop. Here's a simple example with event handling:

import pygame
pygame.init()
picture = pygame.image.load("cards/S01.png")

# display.set_mode already returns the screen surface
screen = pygame.display.set_mode(picture.get_size())

# a simple flag to show if the application is running
# there are other ways to do this, of course
running = True
while running:

    # it's important to get all events from the 
    # event queue; otherwise it may get stuck
    for e in pygame.event.get():
        # if there's a QUIT event (someone wants to close the window)
        # then set the running flag to False so the while loop ends
        if e.type == pygame.QUIT:
            running = False

    # draw stuff
    screen.blit(picture, (0,0))
    pygame.display.update()

This way, your application does not, only when someone closes the window.



来源:https://stackoverflow.com/questions/31530862/trying-to-display-a-png-file-in-pygame-using-pygame-display-update-and-it-shows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!