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

前端 未结 2 1095
情歌与酒
情歌与酒 2021-01-23 13:26

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:



        
相关标签:
2条回答
  • 2021-01-23 13:45

    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.

    0 讨论(0)
  • 2021-01-23 14:03

    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.

    0 讨论(0)
提交回复
热议问题