时间间隔后如何显示图像? [英] How to display an image after a time interval?

查看:66
本文介绍了时间间隔后如何显示图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to display an image 3 seconds after the user has clicked the left mouse button. Here's a part of my code:

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

仅显示一会儿。我尝试在循环中使用循环,但是,它停顿了几秒钟,然后显示了闪光。

It is only displayed a moment. I tried using for and while loops, however, it stutters some seconds and then shows a flash.

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

I think that I can maybe use a timer, add 3s, like so:

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

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

How can I write this code paragraph? And are there better ways?

推荐答案

当用户单击鼠标按钮时启动计时器,然后在主菜单中计算经过的时间循环,如果> = 3 ,则将图像变暗。

Start the timer when the user clicks a mouse button, then calculate the passed time in the main loop and if it's >= 3, blit the image.

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

这篇关于时间间隔后如何显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆