上/下鼠标之间的秒表

2024-04-24 00:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过在while循环中使用一个简单的秒表来测试鼠标按下和鼠标上升事件之间的时间。mouse down事件可以正常工作,但是当我释放鼠标进行鼠标向上移动时,秒数会继续向上移动并且不会停止

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秒


Tags: importeventtruenewiftimetypedisplay
1条回答
网友
1楼 · 发布于 2024-04-24 00:22:55

使用^{}获取自调用pygame.init()以来的毫秒数。
存储MOUSEBUTTONDOWN时的毫秒数并计算主循环中的时差:

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

相关问题 更多 >