gpt4 book ai didi

python - 鼠标向上/向下之间的秒表

转载 作者:太空宇宙 更新时间:2023-11-04 04:12:40 25 4
gpt4 key购买 nike

我试图通过在 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()

关于python - 鼠标向上/向下之间的秒表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56062519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com