2

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

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。

4

1 回答 1

1

用于pygame.time.get_ticks获取自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()
于 2019-05-09T15:48:30.840 回答