Is it possible to detect if the mouse is held down with python

Question:

Does anyone know if its possible to detect if the cursor is being held down with python? I was thinking something like this:

while mouseDown == True:
    # some other code

I am quite new to python, so I apologise if I missed a really obvious solution.

Asked By: Gurnoor

||

Answers:

You can use pygame to handle events like these:

import pygame

(width, height) = (400, 250)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Title')
screen.fill((255,255,255))
pygame.display.flip()    

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            # your code here
        if event.type == pygame.QUIT:
            running = False

You can also control the number of times pygame checks if the mouse button is pressed down (called FPS if you are not familiar with game terminology):

import pygame

(width, height) = (400, 250)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Title')
screen.fill((255,255,255))
pygame.display.flip()    

running = True
clock = pygame.time.Clock()
while running:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            # your code here
        if event.type == pygame.QUIT:
            running = False
    clock.tick(30) # capped at 30 fps
Answered By: PranavaGande

pynput works very well for mouse and keyboard automation. This simple script should help you get started:

from pynput.mouse import Listener

def on_move(x, y):
    pass

def on_click(x, y, button, pressed):
    if pressed:
        # Your code here

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

with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()
Answered By: torchhound

You can use pynput module to do it. It can be installed using pip command pip install pynput. Also, see the documentation to understand the full functionality of pynput. Basically it is used to log key input of keyboard and mouse.

Here is how you can check if the mouse key is held down or not.

from pynput.mouse import Listener

# This function will be called when any key of mouse is pressed
def on_click(*args):
    # see what argument is passed.
    print(args)
    if args[-1]:
        # Do something when the mouse key is pressed.
        print('The "{}" mouse key has held down'.format(args[-2].name))

    elif not args[-1]:
        # Do something when the mouse key is released.
        print('The "{}" mouse key is released'.format(args[-2].name))

# Open Listener for mouse key presses
with Listener(on_click=on_click) as listener:
    # Listen to the mouse key presses
    listener.join()
Answered By: Saad

Does anyone know if its possible to detect if the cursor is being held down with python?

A mouse is nothing more than an input device. Depending on the operating system and its configuration you need to see how the input/output events are processed.

This is the job of the a https://en.wikipedia.org/wiki/Display_server on *nix system.

If you target a specific operating system then you need to check the documentation (on *nix systems you are probably using x.org or wayland on windows on mac you need to check their docs)

If you need this working everywhere you need to create the boilerplate code that identifies the operating system and gets the event. In *nix you could theoritically start reading from /dev but its better if you use the native interfaces given to you

Or the best thing would be to just find a library that does all this for you, https://pypi.org/project/pynput/ looks like a good candidate.

Answered By: George Daramouskas

I’ve been looking for this one and found this easier code to implement.

import win32api

while True:
    if win32api.GetKeyState(0x01)<0: #if mouse left button is pressed
       print("Pressed")
    else: #if mouse left button is not pressed
       print("Released")

This allows you to check in real time if mouse left is held or not.

I made button holding detector within the tkinter window.

from tkinter import *

left_click = False

def left_click_start(event):
    global left_click
    left_click = True

def left_click_stop(event):
    global left_click
    left_click = False

win = Tk()

win.bind("<Button-1>", click_start)
win.bind("<B1-ButtonRelease>", click_stop)

while True:
    if left_click:
        # put the code here
    win.update()

Answered By: Robert
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.