0
我的主要想法是计算鼠标移动的时间。我想启动python脚本,并从一开始就花时间。 Idk如何在清晰的Python中做到这一点,但是我读到Qt,在这个任务中看起来很有帮助。但我从来没有使用它,我看到很多关于跟踪鼠标移动的信息,但是我可以计算时间吗?怎么做?如何用python捕获鼠标移动?
我的主要想法是计算鼠标移动的时间。我想启动python脚本,并从一开始就花时间。 Idk如何在清晰的Python中做到这一点,但是我读到Qt,在这个任务中看起来很有帮助。但我从来没有使用它,我看到很多关于跟踪鼠标移动的信息,但是我可以计算时间吗?怎么做?如何用python捕获鼠标移动?
目前尚不清楚您想要计算什么时间。以下代码将根据当前鼠标位置和每次鼠标移动时的最后鼠标位置打印每秒像素数的速度。
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_()
编辑:您可以使用以下在一个无限循环,而不是鼠标事件在整个屏幕上跟踪鼠标移动速度窗口之外,这个时间码。但是,如果您来回移动鼠标,如果轮询间隔过长,那么这些距离可能会互相抵消。
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)
谢谢,我有想法如何修改这个脚本,他会执行我的任务! –