如何用Python pyglet检测双击事件?

0 投票
1 回答
2128 浏览
提问于 2025-04-18 02:03

我查看了pyglet的鼠标事件,它很好地处理了常见的鼠标操作,比如点击、拖动和释放鼠标按钮。我想处理双击事件,但这似乎没有那么简单。

我是不是应该监控鼠标按下和释放的事件,然后比较时间间隔和位置来检测双击事件呢?

我不想重复造轮子。有没有什么“最佳实践”可以用来在pyglet中检测双击事件呢?

这是我目前想到的最好方法:

import time
import pyglet

class MyDisplay:
    def __init__(self):
        self.window = pyglet.window.Window(100, 100)

        @self.window.event
        def on_mouse_release(x, y, button, modifiers):
            self.last_mouse_release = (x, y, button, time.clock())

        @self.window.event
        def on_mouse_press(x, y, button, modifiers):
            if hasattr(self, 'last_mouse_release'):
                if (x, y, button) == self.last_mouse_release[:-1]:
                    """Same place, same button"""
                    if time.clock() - self.last_mouse_release[-1] < 0.2:
                        print "Double-click"

1 个回答

2

从源代码来看,pyglet 似乎是通过 time.time() 来计算点击之间的时间。

为了更好地说明我的意思,这里有一小段来自 pyglet 源代码的摘录:

t = time.time()
if t - self._click_time < 0.25:
    self._click_count += 1
else:
    self._click_count = 1
    self._click_time = time.time()

(完整的函数版本可以在 这里 找到。请注意,完整版本的代码是为了选择文本而设计的。)

源代码还暗示了使用一个图形用户界面工具包,这样它就可以监控点击事件。

撰写回答