Block mouse click in Python

Viewed 577

I am working on a little Mouse Spamming Stopper script in Python and I don't really know how can I only block the mouse click, but still be able to move the mouse.

This is what I got so far:

from pynput.mouse import Listener
import time


mouse_allowed = True

def timeout():
    mouse_allowed = False
    time.sleep(0.1)

def on_click(x, y, button, pressed):
    if mouse_allowed:
        print("Clicked")
        timeout()

if mouse_allowed:
    with Listener(on_click=on_click) as listener:
        listener.join()
1 Answers

One way that I found to get around the mouse being locked is to check the time. This can be done by using the time.time() function. Here is a rough example snippet of what I mean.

from pynput.mouse import Listener
import time

last_click = time.time()

def good_click_time():
    # Make sure the program knows that it's getting the global variable
    global last_click
    # Makes sure that 1 second has gone by since the last click
    if time.time() - last_click > 1:
        # Records last click
        last_click = time.time()
        return True
    else:
        return False

def on_click(x, y, button, pressed):
    if good_click_time():
        print("Clicked")
    else:
        print("You must wait 1 second to click. You have waited {} seconds".format(time.time() - last_click))

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

By recording the exact time you last clicked you can use that to check if it's been at least a second (or however long you want between your clicks) since your last click.

Related