问题
I am able to display a number "1" on my display. Now, my goal is to display the numbers 1...4. That means "1" is displayed first, then after 1 "2" is displayed, etc. How to solve that problem?
Here is my code:
import pygame
import time
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
done = False
font = pygame.font.SysFont("comicsansms", 72)
text = font.render("1", True, (0, 128, 0))
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
screen.fill((255, 255, 255))
screen.blit(text,
(320 - text.get_width() // 2, 240 - text.get_height() // 2))
pygame.display.flip()
clock.tick(60)
回答1:
Create a counter and us str() to convert a value to a string:
counter = 1
text = font.render(str(counter), True, (0, 128, 0))
Add a timer event (see pygame.event) with a certain time interval. A timer event is started by pygame.time.set_timer()
mytimerevent = pygame.USEREVENT + 1
pygame.time.set_timer(mytimerevent, 1000) # 1000 milliseconds = 1 socond
Increment the counter and change the text on the event:
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
if event.type == mytimerevent: # timer event
counter += 1
text = font.render(str(counter), True, (0, 128, 0))
# [...]
回答2:
Update text
each frame like so:
# Setup stuff
number = 1
text = font.render(str(number), True, (0, 128, 0))
while not done:
# Show stuff on screen
number += 1
text = font.render(str(number), True, (0, 128, 0))
来源:https://stackoverflow.com/questions/56453574/how-to-display-dynamically-in-pygame