我试图通过在 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。
请您参考如下方法:
使用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()
