【问题标题】:Cursor not moving to originial spot pynput光标未移动到原始点 pynput
【发布时间】:2021-10-29 12:44:55
【问题描述】:

我当前的代码如下所示:

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()

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

【问题讨论】:

    标签: python python-3.x pynput


    【解决方案1】:

    不起作用。为什么?

    您当前实现的逻辑如下所示:
    在鼠标点击时,如果是右键(无论是按下还是释放),将当前鼠标坐标存储在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 视为代码异味,因此这里有一个更好、更高级的解决方案,带有一个类:

    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()
    

    【讨论】:

    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多