python - 经过一段时间后如何更新显示的元素?

标签 python list pygame display

我在 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

最佳答案

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

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)

关于python - 经过一段时间后如何更新显示的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56470306/

相关文章:

javascript - 检查字符串是否在列表中(JavaScript)

python - 将多个元素(基于条件)移动到列表末尾

eclipse - 如何让 Pygame 与 Pydev 一起工作?

python - 在 Pygame 中获取键盘输入的更简单方法?

python - 将列表中的单词打印到 pygame 中的特定坐标

python - 使用 python 保留关键字作为变量名

machine-learning - 数据集在循环变量列表时抛出 KeyError

python - 如何通过 telnet 运行 Python 程序?

python - 在 for 循环中使用 if 语句时 python 中的缩进错误

c++ - 如何在 C++ 中返回一个列表