Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Check if mouse clicked

I'm trying to build a short script in Python, where if the mouse is clicked, the mouse will reset to some arbitrary position (right now the middle of the screen).

I'd like this to run in the background, so it could work with other applications (most likely Chrome, or some web browser). I'd also like it so that a user could hold down a certain button (say CTRL) and they could click away and not have the position reset. This way they could close the script without frustration.

I'm pretty sure I know how to do this, but I'm not sure which library to use. I'd prefer if it was cross-platform, or at least work on Windows and Mac.

Here's my code so far:

#! python3
# resetMouse.py - resets mouse on click - usuful for students with
# cognitive disabilities.

import pymouse

width, height = m.screen_size()
midWidth = (width + 1) / 2
midHeight = (height + 1) / 2

m = PyMouse()
k = PyKeyboard()


def onClick():
    m.move(midWidth, midHeight)


try:
    while True:
        # if button is held down:
            # continue
        # onClick()
except KeyboardInterrupt:
    print('\nDone.')
like image 445
TheDetective Avatar asked Jan 17 '17 04:01

TheDetective


People also ask

How do you check if the mouse is clicked in Python?

import pymouse width, height = m. screen_size() midWidth = (width + 1) / 2 midHeight = (height + 1) / 2 m = PyMouse() k = PyKeyboard() def onClick(): m. move(midWidth, midHeight) try: while True: # if button is held down: # continue # onClick() except KeyboardInterrupt: print('\nDone.

How do I know if my mouse is clicking?

Click all the buttons on your mouse and check if they light up on the mouse illustration. Point your mouse cursor at the mouse illustration and then spin the scroll wheel on your mouse up and down. Check if the arrows on the illustration also light up.

How does Pygame detect mouse press?

The current position of the mouse can be determined via pygame. mouse. get_pos() . The return value is a tuple that represents the x and y coordinates of the mouse cursor.


2 Answers

Try this

from pynput.mouse import Listener


def on_move(x, y):
    print(x, y)


def on_click(x, y, button, pressed):
    print(x, y, button, pressed)


def on_scroll(x, y, dx, dy):
    print(x, y, dx, dy)


with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()
like image 150
Mahamudul Hasan Avatar answered Sep 25 '22 09:09

Mahamudul Hasan


The following code worked perfectly for me. Thanks to Hasan's answer.

from pynput.mouse import Listener

def is_clicked(x, y, button, pressed):
    if pressed:
        print('Clicked ! ') #in your case, you can move it to some other pos
        return False # to stop the thread after click

with Listener(on_click=is_clicked) as listener:
    listener.join()
like image 28
Mujeeb Ishaque Avatar answered Sep 26 '22 09:09

Mujeeb Ishaque