Python pynput - 程序在启动时滞后

Python pynput - program lags upon start

所以我一直在尝试制作一个简单的程序,在单击鼠标右键时,让我的鼠标以 0.5 秒的间隔单击左键 3 次。但是,当我启动该程序并单击鼠标右键时,该程序会执行它被告知要做的事情,但也会开始可怕地滞后大约 25 秒。在它完成滞后并尝试关闭程序后,它冻结了,迫使我通过任务管理器将其关闭。

代码如下:

import time
from pynput.mouse import Button, Controller, Listener

mouse = Controller()

def on_click(x, y, button, pressed):
    if button == Button.right:
        num = 3
        while num > 0:
            time.sleep(0.5)
            mouse.click(Button.left)
            num -= 1

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

非常感谢任何帮助。

您需要使用 pressed 变量。 好像保存的是按钮是按下还是松开的值

如果没有这个,循环也会在释放时重复另一次。

这符合我的预期:

import time
from pynput.mouse import Button, Controller, Listener

mouse = Controller()

def on_click(x, y, button, pressed):
    if button == Button.right and pressed:
        num = 3
        while num > 0:
            print("Clicked")
            time.sleep(0.5)
            mouse.click(Button.left)
            num -= 1
        print("Done")

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

经过一段时间的调试和挖掘问题后,pynput.mouse.Listener 在 Windows 机器上移动鼠标时似乎有一些问题 hanging/lagging。

在 Linux 机器上,开箱即用,没有挂起或滞后。