【问题标题】:How to display dynamically in Pygame? [duplicate]如何在 Pygame 中动态显示? [复制]
【发布时间】:2019-06-05 02:31:00
【问题描述】:

我可以在我的显示器上显示一个数字“1”。现在,我的目标是显示数字 1...4。即先显示“1”,再显示1后显示“2”,以此类推。如何解决?

这是我的代码:

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)

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    创建一个计数器并使用str() 将值转换为字符串:

    counter = 1
    text = font.render(str(counter), True, (0, 128, 0))
    

    添加具有特定时间间隔的计时器事件(请参阅pygame.event)。定时器事件由pygame.time.set_timer()启动

    mytimerevent = pygame.USEREVENT + 1
    pygame.time.set_timer(mytimerevent, 1000) # 1000 milliseconds = 1 socond 
    

    增加计数器并更改事件的文本:

    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))
    
    
        # [...]
    

    【讨论】:

    • 嘿伙计,如果我想按一个按钮使这个功能起作用,我该如何解决这个问题?
    • @DerickKolln 不要在主循环之前启动计时器。按下按钮时启动计时器。按钮覆盖一个矩形区域,其位置(x,y)和大小(w,h)。使用b = pygame.Rect(x, y, w, h)if event.type == pygame.MOUSEBUTTONDOWN and b.rect.collidepoint(event.pos): pygame.time.set_timer(mytimerevent, 1000)。另见Call function by button click in Pygame
    【解决方案2】:

    像这样更新text每一帧:

    # 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))
    

    【讨论】:

      猜你喜欢
      • 2014-01-17
      • 2019-03-23
      • 2021-03-31
      • 2022-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      相关资源
      最近更新 更多