光标未移动到原始点 pynput

Cursor not moving to originial spot pynput

我当前的代码如下所示:

from pynput.mouse import Button, Controller, Listener

mouse = Controller()

def on_click(x, y, button, pressed):
    if button == Button.right:
        placeX = x
        placeY = y
        mouse.position = (placeX, placeY) # Doesn't work. Why?


with Listener(
        on_click=on_click
) as listener:
    listener.join()

我的目标是在释放鼠标右键后将光标放回原来的位置。当我测试它时,什么也没有发生。我如何让它工作?

不起作用。为什么?

您当前实现的逻辑如下所示:
鼠标点击时,如果是右键(不管是按下还是松开),将当前鼠标坐标存入placeXplaceY,并立即将鼠标移动到该位置。

效率不高,因为鼠标已经在这个位置了。

如何修复?

检查鼠标是否松开

def on_click(x, y, button, pressed):
    if pressed:
        ...  # remember the position
    else:
        ...  # return to position

检查鼠标按钮

def on_click(x, y, button, pressed):
    if button != Button.right:
        return  # we don't care

    if pressed:
        ...  # remember the position
    else:
        ...  # return to position

保存原位置

# in case the mouse was pressed and not released when starting the program
original_position = mouse.position

def on_click(x, y, button, pressed):
    if button != Button.right:
        return  # we don't care

    global original_position 

    if pressed:
        original_position = mouse.position  # remember the position
    else:
        mouse.position = original_position  # return to position

我们在这里使用关键字global,以便我们以后可以更改全局变量的值。

享受

:)

备选

请注意,我通常认为 global 是一种代码味道,所以这里有一个更好、更高级的解决方案 class:

from pynput.mouse import Button, Controller, Listener

mouse = Controller()


class Mover:
    def __init__(self, original_position=mouse.position):
        self.original_position = original_position

    def on_click(self, x, y, button, pressed):
        if button != Button.right:
            return  # we don't care

        if pressed:
            self.original_position = mouse.position  # remember the position
        else:
            mouse.position = self.original_position  # return to position


mover = Mover()

with Listener(
        on_click=mover.on_click
) as listener:
    listener.join()