鼠标上/下之间的秒表 [英] Stopwatch between mouse up/down

查看:94
本文介绍了鼠标上/下之间的秒表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过在 while 循环中使用一个简单的秒表来测试鼠标按下和鼠标抬起事件之间的时间.鼠标按下事件工作正常,但是当我松开鼠标以将鼠标抬起时,秒数继续上升并且不会停止.

I am trying to test the time between mouse down and mouse up events by using a simple stopwatch in a while loop. The mouse down event works fine, but when i release the mouse for mouse up, the seconds continue to go up and do not stop.

from pygame import *
import time
screen = display.set_mode((160, 90))
sec = 0
while True:
    new_event = event.poll()
    if new_event.type == MOUSEBUTTONDOWN:
        while True: # Basic stopwatch started
            time.sleep(1)
            sec += 1
            print(sec)
            # In loop, when mouse button released,
            # supposed to end stopwatch
            if new_event.type == MOUSEBUTTONUP:
                break
    display.update()

我希望在释放鼠标后秒表结束.例如.如果鼠标刚刚点击,秒应该是1.如果鼠标保持5秒,它应该不会继续超过5.

I want the stopwatch to end after the mouse is released. eg. If the mouse is just clicked, the seconds should be 1. If the mouse is held for 5 seconds, it should not continue past 5.

推荐答案

使用 pygame.time.get_ticks 获取自 pygame.init() 被调用以来的毫秒数.
存储MOUSEBUTTONDOWN时的毫秒数,并计算主循环中的时间差:

Use pygame.time.get_ticks to get the number of milliseconds since pygame.init() was called.
Store the milliseconds when MOUSEBUTTONDOWN and calculate the time difference in the main loop:

from pygame import *

screen = display.set_mode((160, 90))

clock = time.Clock()
run = True
started = False
while run:

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

        if new_event.type == MOUSEBUTTONDOWN:
            start_time = time.get_ticks()
            started = True

        if new_event.type == MOUSEBUTTONUP:
            started = False

    if started:        
        current_time = time.get_ticks()
        sec = (current_time - start_time) / 1000.0
        print(sec)

    display.update()

这篇关于鼠标上/下之间的秒表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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