Python pynput - program lags upon start

梦想与她 提交于 2020-12-12 09:59:26

问题


So I've been trying to make a simple program that, upon clicking the right mouse button, makes my mouse click the left button 3 times in 0.5 second intervals. However, when I start the program and do right click, the program does what it's told to do but also starts lagging horrendously for about 25 seconds. After it's done lagging and I try to close the program, it freezes, forcing me to close it via task manager.

The code is as follows:

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

Any help is greatly appreciated.


回答1:


After some time debugging and digging though issues, it seems that pynput.mouse.Listener has a few problems hanging/lagging on Windows machines when moving the mouse.

On a Linux machine, things should work fine out of the box with no hanging or lagging.




回答2:


You need to make use of the pressed variable. It seems to hold the value of whether the button is pressed or released.

Without this, the loop repeats another time when it is released as well.

This works as expected for me:

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


来源:https://stackoverflow.com/questions/54728076/python-pynput-program-lags-upon-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!