【问题标题】:Stopwatch between mouse up/down鼠标上/下之间的秒表
【发布时间】:2020-05-27 07:54:43
【问题描述】:

我正在尝试通过在 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。

【问题讨论】:

    标签: python pygame pygame-clock


    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      相关资源
      最近更新 更多