如何在一段时间后显示图像?

时间:2017-08-10 09:02:15

标签: python python-3.x pygame display

我想在用户点击鼠标左键3秒后显示图像。 这是我的代码的一部分:

pic=pygame.image.load('pic.png')
while True:
  for event.type==pygame.MOUSEBUTTONDOWN:
    screen.blit(pic,(100,100))

只显示片刻。我尝试使用forwhile循环,然而,它会停顿几秒钟然后显示闪光灯。

我认为我可以使用计时器,添加3s,如下:

for event.type==pygame.MOUSEBUTTONDOWN:
  #get now time here,and assignment for timeclick
if timeclick+3s>=timenow:  # pseudocode
  screen.blit(pic,(100,100))

如何编写此代码段落?还有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

当用户点击鼠标按钮时启动计时器,然后计算主循环中的传递时间,如果它是>= 3,则显示图像。

import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    font = pg.font.Font(None, 40)
    img = pg.Surface((100, 100))
    img.fill((190, 140, 50))
    click_time = 0
    passed_time = 0

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            # Start the timer.
            elif event.type == pg.MOUSEBUTTONDOWN:
                click_time = pg.time.get_ticks()

        screen.fill((30, 30, 30))
        if click_time != 0:  # If timer has been started.
            # Calculate the passed time since the click.
            passed_time = (pg.time.get_ticks()-click_time) / 1000

        # If 3 seconds have passed, blit the image.
        if passed_time >= 3:
            screen.blit(img, (50, 70))

        txt = font.render(str(passed_time), True, (80, 150, 200))
        screen.blit(txt, (50, 20))

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

答案 1 :(得分:0)

您必须在主应用程序循环中绘制图像。使用pygame.time.get_ticks()返回自pygame.init()被调用以来的毫秒数。发生MOUSEBUTTONDOWN事件时,请计算必须显示图像之后的时间点。在当前时间大于计算的时间点后显示图像:

import pygame
pygame.init()
screen= pygame.display.set_mode((800, 600))

#pic = pygame.image.load('pic.png')
pic = pygame.Surface((100, 100))
pic.fill((255, 255, 255))
pic_time = 0

run = True
while run:
    current_time = pygame.time.get_ticks()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            pic_time = current_time + 3000 # 3000 milliseconds == 3 seconds

    screen.fill(0)

    if pic_time > 0 and current_time >= image_time:
        screen.blit(pic,(100,100))

    pygame.display.flip()

pygame.quit()