2017-03-06 92 views
0

我的主要想法是計算鼠標移動的時間。我想啓動python腳本,並從一開始就花時間。 Idk如何在清晰的Python中做到這一點,但是我讀到Qt,在這個任務中看起來很有幫助。但我從來沒有使用它,我看到很多關於跟蹤鼠標移動的信息,但是我可以計算時間嗎?怎麼做?如何用python捕獲鼠標移動?

回答

-1

目前尚不清楚您想要計算什麼時間。以下代碼將根據當前鼠標位置和每次鼠標移動時的最後鼠標位置打印每秒像素數的速度。

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) 
+0

謝謝,我有想法如何修改這個腳本,他會執行我的任務! –