我需要用pygame制作一个计时器

-2 投票
2 回答
3807 浏览
提问于 2025-04-18 06:53

我做了一个秒表,但它只在IDLE里显示。我在那儿有我的pygame窗口,但我不知道怎么才能让秒表在pygame窗口里显示出来。我试过不同的方法,但就是不知道怎么让它在窗口里显示。

import time
import pygame
from pygame.locals import *
import sys, os
pygame.init()


background_colour = (255,255,255)
(width, height) = (720, 480)

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Tutorial 1')
screen.fill(background_colour)
myfont = pygame.font.SysFont("monospace", 25)

label = myfont.render("countdown", 1, (0,0,0))
screen.blit(label, (100, 100))

pygame.display.flip()

def cronos():
    clock = pygame.time.Clock()
    minutes = 0
    seconds = 0
    milliseconds = 0

    while True: #game loop
        #do stuff here
        if milliseconds > 1000:
            seconds += 1
            milliseconds -= 1000
        if seconds > 60:
            minutes += 1
            seconds -= 60

        print ("{}:{}".format(minutes, seconds))

        milliseconds += clock.tick_busy_loop(60)

2 个回答

0

为了防止数字重叠,你可以添加一些类似下面的内容:

clock = pygame.time.Clock()
minutes = 0
seconds = 0
milliseconds = 0

cover = pygame.surface.Surface((160,40)).convert()
cover.fill((220, 220, 220))
while True:
    if milliseconds > 1000:
        seconds += 1
        milliseconds -= 1000
        screen.blit(cover, (0,0))
        pygame.display.update()

    if seconds > 60:
        minutes += 1
        seconds -= 60
    milliseconds += clock.tick_busy_loop(60)
    timelabel = myfont.render("{}:{}".format(minutes, seconds), True, (0,0,0))
    screen.blit(timelabel,(0, 0))


    pygame.display.update()
0

只需要添加一个标签,然后在你的 while True 循环中进行绘制:

#...
while True:
    timelabel = myfont.render("{}:{}".format(minutes, seconds), 1, (0,0,0))
    screen.blit(timelabel, (200, 100))
    #Rest of your code

撰写回答