python记录鼠标滑动轨迹

一个记录鼠标轨迹的程序。

一直需要一个记录鼠标轨迹的程序,本想找一个,但是都不太合适,所以就自己写了一个。功能很简单,就是记录鼠标按下时的滑动轨迹。

from pynput import mouse


class Orbit(object):
    def __init__(self, min_x=-10000, min_y=-10000, max_x=10000, max_y=10000,):
        """可以设置滑动轨迹的范围,x轴和y轴移动的最小值和最大值。
        """
        # 默认的鼠标左键是松开的
        self.left_pressed = False
        self.mouse_x = 0
        self.mouse_y = 0
        self.mouse_list = []
        self.min_x = min_x
        self.min_y = min_y
        self.max_x = max_x
        self.max_y = max_y

    def on_move(self, x, y):
        """移动鼠标时会触发这个函数。

            x,y为鼠标的绝对坐标。
        """ 
        # 当按下鼠标左键的时候开始打印轨迹,松开时结束。
        if self.left_pressed:
            # 打印和记录的是移动的相对距离。
            print(f"({x-self.mouse_x}, {y-self.mouse_y})")
            self.mouse_list.append((x-self.mouse_x, y-self.mouse_y))

    def on_click(self, x, y, button, pressed):
        """点击鼠标时会触发这个函数。

            x,y为鼠标的绝对坐标。button为点击的左键还是右键。pressed为鼠标的按压状态,按下时为True。
        """ 
        print('pressed:', pressed, 'button: ', button)
        # 按下鼠标左键开始记录鼠标轨迹。
        if str(button) == "Button.left" and pressed:
            self.left_pressed = True
            self.mouse_x = x
            self.mouse_y = y
            self.mouse_list = []
        # 松开鼠标左键的饰扣开始打印轨迹。
        if str(button) == "Button.left" and not pressed:
            self.left_pressed = False
            if self.mouse_list and self.min_x < self.mouse_list[-1][0] < self.max_x and \
                    self.min_y < self.mouse_list[-1][1] < self.max_y:
                print(self.mouse_list)
        # 按下鼠标右键的时候停止记录鼠标轨迹。
        if str(button) == "Button.right" and pressed:
            return False

    def start(self):
        with mouse.Listener(on_move=self.on_move, on_click=self.on_click) as listener:
            listener.join()
        # 需要监听的鼠标事件。
        listener = mouse.Listener(
            on_move=self.on_move,
            on_click=self.on_click,
            suppress=False
        )
        # 开始监听
        listener.start()


if __name__ == '__main__':
    move_track = Orbit(min_x=-164, max_x=-144, min_y=188, max_y=208)
    move_track.start()

pynput 还可以监听鼠标滑轮,如有别的需求可自己修改。

你可能感兴趣的:(python记录鼠标滑动轨迹)