简体   繁体   English

如何创建可视计时器?

[英]How to create a visual timer?

I'm currently struggling with formatting the count up timer for my code.我目前正在为我的代码格式化计数计时器而苦苦挣扎。 I want a regular timer that counts up in milliseconds, however, I can't figure out how to visually show this on the timer.我想要一个以毫秒为单位计数的常规计时器,但是,我无法弄清楚如何在计时器上直观地显示它。 At the moment it only shows milliseconds as opposed to minutes, seconds and milliseconds, so once the timer hits 100 milliseconds it simply keeps counting this way instead of 1 second 0 milliseconds.目前它只显示毫秒,而不是分钟、秒和毫秒,所以一旦计时器达到 100 毫秒,它就会继续以这种方式计数,而不是 1 秒 0 毫秒。 How can I get this to work?我怎样才能让它工作?

import pygame
pygame.init()

screen = pygame.display.set_mode((450, 600))

timer_font = pygame.font.SysFont("Calibri", 38)
timer_sec = 0
timer_text = timer_font.render("00:00:00", True, (255, 255, 255))


timer = pygame.USEREVENT + 0                                      
pygame.time.set_timer(timer, 10)

running = True
while running:
    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == timer:
            if timer_sec < 600:
                timer_sec += 1
                timer_text = timer_font.render("00:00:%02i" % timer_sec, True, (255, 255, 255))
            else:
                pygame.time.set_timer(timer, 0)

    screen.blit(timer_text, (300, 20))
    pygame.display.update()

Do not use the timer event for this task as it will lead to inaccuracies.不要为此任务使用计时器事件,因为它会导致不准确。 Usepygame.time.get_ticks() and calculate the hours, minutes and seconds in each frame.使用pygame.time.get_ticks()并计算每一帧中的小时、分钟和秒。 Render a new time text when the time has changed:当时间改变时渲染一个新的时间文本:

import pygame
pygame.init()

screen = pygame.display.set_mode((450, 600))
timer_font = pygame.font.SysFont("Calibri", 38)

start_time = pygame.time.get_ticks()
time_hms = 0, 0, 0
timer_surf = timer_font.render(f'{time_hms[0]:02d}:{time_hms[1]:02d}:{time_hms[2]:02d}', True, (255, 255, 255))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    time_ms = pygame.time.get_ticks() - start_time
    new_hms = (time_ms//(1000*60*60))%24, (time_ms//(1000*60))%60, (time_ms//1000)%60
    if new_hms != time_hms:
        time_hms = new_hms
        timer_surf = timer_font.render(f'{time_hms[0]:02d}:{time_hms[1]:02d}:{time_hms[2]:02d}', True, (255, 255, 255))

    screen.fill(0)
    screen.blit(timer_surf, (300, 20))
    pygame.display.update()

pygame.quit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM