計算したい時間が不明です。次のコードは、現在のマウスの位置と各マウスの動きの最後のマウスの位置に基づいて、秒当たりのピクセル数で速度を表示します。
import sys
import math
import time
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
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)
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_()
EDIT:あなたは無限ループに代わりのマウスイベントに、この時間を画面全体にウィンドウのマウスの移動速度の外を追跡するための次のコードを使用することができます。ただし、マウスを前後に動かすと、ポーリング間隔が長すぎると、それらの距離が互いに打ち消し合うことがあります。
import sys
import math
import time
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
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)
return d/time_delta
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2-y1)**2)
def get_current_cursor_position():
pos = QCursor.pos()
return pos.x(), pos.y()
def get_current_frame():
return Frame(get_current_cursor_position(), time.time())
if __name__ == '__main__':
app = QApplication(sys.argv)
last_frame = get_current_frame()
while True:
new_frame = get_current_frame()
print(new_frame.speed(last_frame))
last_frame = new_frame
time.sleep(0.1)
ありがとう、私はこのスクリプトを修正する方法を知っている、彼は私の仕事を実行するだろう! –