【问题标题】:How to update elements on display after passed time?经过一段时间后如何更新显示的元素?
【发布时间】:2019-10-21 13:02:48
【问题描述】:

我在 Pygame 中有一个程序,它允许我显示列表 list 中的元素。每 3 秒,它更新并显示来自list 的下一个元素。 我的问题是元素在屏幕上重叠,但我想在每次 3 秒后更新它。我已经用过:

pygame.display.update()

但它不起作用。

list = ["x", "y", "z"]
if time > 3 and i < len(list):
    font = pygame.font.SysFont("comicsansms", 72)
    text2 = font.render(str(list[i]), True, (0, 128, 0))

    screen.blit(text2,
                (430 - text2.get_width() // 1, 220 - text2.get_height() // 2))

    pygame.display.update()
    pygame.display.flip()
    clock.tick(30)
    i = i + 1

【问题讨论】:

    标签: python list pygame display


    【解决方案1】:

    以下内容每三秒更新一次显示内容:

    import sys
    import time
    import pygame
    from pygame.locals import *
    
    pygame.init()
    
    FPS = 30
    WINDOWWIDTH = 640
    WINDOWHEIGHT = 480
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    clock = pygame.time.Clock()
    font = pygame.font.SysFont("comicsansms", 72)
    
    screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    pygame.display.set_caption('Test')
    
    my_list = ["x", "y", "z"]
    bkgr = BLACK
    i = len(my_list) - 1  # Index of last elememnt (so first is next displayed).
    start_time = 0
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
    
        if (time.time() - start_time) > 3:  # 3 seconds since last update?
            i = (i + 1) % len(my_list)
            start_time = time.time()
    
            screen.fill(bkgr)
            text2 = font.render(str(my_list[i]), True, (0, 128, 0))
            screen.blit(text2, (430 - text2.get_width() // 1,
                                220 - text2.get_height() // 2))
            pygame.display.update()
    
        clock.tick(FPS)
    

    【讨论】:

    • 谢谢。哪一行代码更新了屏幕?是 {pygame.display.update()} 吗?我在我的第一个代码中也使用了它,但什么也没发生。
    • 是的,pygame.display.update() 是更新显示的行。抱歉,我不太确定您的代码有什么问题,其中遗漏了太多内容,我无法确定问题所在——它可能是许多不同事物中的任何一种。
    • 谢谢马蒂诺。我想提出另一个类似的问题。也许你也可以帮忙。
    • 还有一个问题:如果你想更新屏幕,clock.tick() 总是需要的,对吧?
    • 它并不是严格需要的——尤其是在这个延迟更新的例子中——尽管docs确实说它“应该每帧调用一次”。
    猜你喜欢
    • 1970-01-01
    • 2017-01-14
    • 2017-06-07
    • 2016-11-23
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    相关资源
    最近更新 更多