不清楚你要计算什么时候。下面的代码将根据每次鼠标移动时的当前鼠标位置和最后一个鼠标位置打印速度(以像素为单位)。在import sys
import math
import time
from PyQt5.QtWidgets import QApplication, QMainWindow
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
class Frame:
def __init__(self, position, time):
self.position = position
self.time = time
def speed(self, frame):
d = distance(*self.position, *frame.position)
time_delta = abs(frame.time - self.time)
if time_delta == 0:
return None
else
return d / time_delta
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.last_frame = None
self.setMouseTracking(True)
def mouseMoveEvent(self, event):
new_frame = Frame((event.x(), event.y()), time.time())
if self.last_frame:
print(new_frame.speed(self.last_frame))
self.last_frame = new_frame
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.resize(900, 600)
w.show()
app.exec_()
编辑:您可以使用下面的代码在整个屏幕上跟踪鼠标在窗口外的移动速度,这次是在一个无休止的循环中,而不是在鼠标事件上。但是,如果鼠标间隔太长,可能会取消这些距离。在
^{pr2}$