Detecting mouse click python

Detecting Mouse clicks in windows using python

The only way to detect mouse events outside your program is to install a Windows hook using SetWindowsHookEx. The pyHook module encapsulates the nitty-gritty details. Here’s a sample that will print the location of every mouse click:

import pyHook import pythoncom def onclick(event): print event.Position return True hm = pyHook.HookManager() hm.SubscribeMouseAllButtonsDown(onclick) hm.HookMouse() pythoncom.PumpMessages() hm.UnhookMouse() 

You can check the example.py script that is installed with the module for more info about the event parameter.

pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the tutorial:

Any application that wishes to receive notifications of global input events must have a Windows message pump. The easiest way to get one of these is to use the PumpMessages method in the Win32 Extensions package for Python. [. ] When run, this program just sits idle and waits for Windows events. If you are using a GUI toolkit (e.g. wxPython), this loop is unnecessary since the toolkit provides its own.

Solution 2

I use win32api. It works when clicking on any windows.

# Code to check if left or right mouse buttons were pressed import win32api import time state_left = win32api.GetKeyState(0x01) # Left button down = 0 or 1. Button up = -127 or -128 state_right = win32api.GetKeyState(0x02) # Right button down = 0 or 1. Button up = -127 or -128 while True: a = win32api.GetKeyState(0x01) b = win32api.GetKeyState(0x02) if a != state_left: # Button state changed state_left = a print(a) if a < 0: print('Left Button Pressed') else: print('Left Button Released') if b != state_right: # Button state changed state_right = b print(b) if b < 0: print('Right Button Pressed') else: print('Right Button Released') time.sleep(0.001) 

Solution 3

It's been a hot minute since this question was asked, but I thought I'd share my solution: I just used the built-in module ctypes . (I'm using Python 3.3 btw)

import ctypes import time def DetectClick(button, watchtime = 5): '''Waits watchtime seconds. Returns True on click, False otherwise''' if button in (1, '1', 'l', 'L', 'left', 'Left', 'LEFT'): bnum = 0x01 elif button in (2, '2', 'r', 'R', 'right', 'Right', 'RIGHT'): bnum = 0x02 start = time.time() while 1: if ctypes.windll.user32.GetKeyState(bnum) not in [0, 1]: # ^ this returns either 0 or 1 when button is not being held down return True elif time.time() - start >= watchtime: break time.sleep(0.001) return False 

Solution 4

Windows MFC, including GUI programming, is accessible with python using the Python for Windows extensions by Mark Hammond. An O'Reilly Book Excerpt from Hammond's and Robinson's book shows how to hook mouse messages, .e.g:

self.HookMessage(self.OnMouseMove,win32con.WM_MOUSEMOVE) 

Raw MFC is not easy or obvious, but searching the web for python examples may yield some usable examples.

Читайте также:  Textarea in html properties

Solution 5

The windows way of doing it is to handle the WM_LBUTTONDBLCLK message.

For this to be sent, your window class needs to be created with the CS_DBLCLKS class style.

I'm afraid I don't know how to apply this in Python, but hopefully it might give you some hints.

Источник

How To Get Mouse Clicks With Python

This demonstration shows you how to track mouse clicks, movements and even scrolls using the pynput module. These can then be logged to a file as no console is displayed. This is very similar to a mouse logger.

If you haven't used or setup pip before, go to my tutorial at how-to-setup-pythons-pip to setup pip.

We will be using the pynput module to listen to mouse events. To install this module execute pip install pynput in cmd. Watch the output to make sure no errors have occurred; it will tell you when the module has been successfully installed.

Installing pynput

To double-check that it was installed successfully, open up IDLE and execute the command import pynput ; no errors should occur.

Testing pynput

Create a new python file and save it with a .py file extension. You will first want to import Listener from pynput.mouse.

from pynput.mouse import Listener 

Setup the listener by creating an instance in a with statement and using it's .join() method to join it to the main thread.

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

Create three methods; on_move, on_click and on_scroll with the parameters as shown below.

def on_move(x, y): pass def on_click(x, y, button, pressed): pass def on_scroll(x, y, dx, dy): pass 

Link these methods to the listener instance with the function names as the args; I have named the methods as they are defined in the listener class. Now when an action occurs, one of these methods will be run.

with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener: 

To make sure these are running, add some print statements to each method. Save and run the script. Move your mouse around a bit, you should see output like below.

def on_move(x, y): print ("Mouse moved") def on_click(x, y, button, pressed): print ("Mouse clicked") def on_scroll(x, y, dx, dy): print ("Mouse scrolled") 

Mouse moved demonstration

Using these print statements and the parameters provided, we can give more information when printing. Run this again to make sure it is working properly (example output below).

def on_move(x, y): print ("Mouse moved to ( , )".format(x, y)) def on_click(x, y, button, pressed): if pressed: print ('Mouse clicked at ( , ) with '.format(x, y, button)) def on_scroll(x, y, dx, dy): print ('Mouse scrolled at ( , )( , )'.format(x, y, dx, dy)) 

Mouse moved demonstration with data

If you want this script to be run in the background. Click File -> Save As and save it with a .pyw file extension. Now when it is run outside IDLE there will be no console window and it will not look like it is running. But to make sure the console doesn't appear, we need to first remove the print statements.

Import logging and setup the basic configuration as I have below. After that, change all print statements to logging.info.

logging.basicConfig(filename="mouse_log.txt", level=logging.DEBUG, format='%(asctime)s: %(message)s') 
def on_move(x, y): logging.info("Mouse moved to ( , )".format(x, y)) def on_click(x, y, button, pressed): if pressed: logging.info('Mouse clicked at ( , ) with '.format(x, y, button)) def on_scroll(x, y, dx, dy): logging.info('Mouse scrolled at ( , )( , )'.format(x, y, dx, dy)) 

Now when the script is run, nothing should be printed to the console. This is because it is all being saved to the file declared in the basic configuration.

Save and close IDLE. Open the file named mouse_log.txt next to your python script; all the events should be logged in here.

The actual location of this file will be in the current working directory of where you run the script from

Just as a quick note, the Listener class is a thread which means as soon as it has joined to the main thread no code will be executed after the .join() until the Listener is stopped.

As stated here in the pynput docs on readthedocs.io, we can call pynput.mouse.Listener.stop anywhere in the script to stop the thread or return False from a callback to stop the listener. As shown in my video, we can also just call listener.stop() in one of the definitions due to the fact that that the listener is now in scope and is an instance os Listener.

from pynput.mouse import Listener import logging logging.basicConfig(filename="mouse_log.txt", level=logging.DEBUG, format='%(asctime)s: %(message)s') def on_move(x, y): logging.info("Mouse moved to ( , )".format(x, y)) def on_click(x, y, button, pressed): if pressed: logging.info('Mouse clicked at ( , ) with '.format(x, y, button)) def on_scroll(x, y, dx, dy): logging.info('Mouse scrolled at ( , )( , )'.format(x, y, dx, dy)) with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener: listener.join() 

Common Issues and Questions

ModuleNotFoundError/ImportError: No module named 'pynput'

Did you install pynput? This error will not occur if you installed it properly. If you have multiple versions of Python, make sure you are installing pynput on the same version as what you are running the script with.

Syntax errors are caused by you and there is not much I can offer to fix it apart from telling you to read the error. They always say where the error is in the output using a ^. Generally people that get this issue have incorrect indentation, brackets in the wrong place or something spelt wrong. You can read about SyntaxError on Python's docs here.

Owner of PyTutorials and creator of auto-py-to-exe. I enjoy making quick tutorials for people new to particular topics in Python and tools that help fix small things.

Источник

Detect mouse clicks in Python with position using pynput

In this tutorial, you will learn how to detect mouse clicks in Python. This program will exactly print the location and the button name which is clicked. We have to install pynput package for this task.

Here we will be only using pynput.mouse to print mouse click events.

Firstly, we need to install pynput package in our Python environment.

Go to cmd and type pip to ensure if it is set up or not. If it is already set up then the cmd console will not generate any errors. After that type pip install pynput in cmd for installing pynput package.

After successfully installing pynput follow the steps of writing code given below.

Detect mouse clicks in Python – Code

Import pynput Python library with the sub-package mouse along with Listener.

from pynput.mouse import Listenerdef click(x,y,button,pressed): print("Mouse is Clicked at (",x,",",y,")","with",button)

Now define a function named click which will take four arguments. (x,y) is the location of the mouse pointer and the button is the name of the button. This function will print the location and button name which is being pressed.

def click(x,y,button,pressed): print("Mouse is Clicked at (",x,",",y,")","with",button)

In the below chunk of code, we use with statement for mouse clicking events which creates the object listener.

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

Now we will see full code.

from pynput.mouse import Listener def click(x,y,button,pressed): print("Mouse is Clicked at (",x,",",y,")","with",button) with Listener(on_click=click) as listener: listener.join()

It will produce the output as shown below. We have successfully detected our mouse clicks.

Mouse is Clicked at ( 729 , 403 ) with Button.left Mouse is Clicked at ( 729 , 403 ) with Button.right Mouse is Clicked at ( 729 , 403 ) with Button.right

We have successfully detected mouse clicks.

Источник

How to detect mouse clicks in Pygame

Here in this tutorial, we will learn how to detect mouse clicks in Python with the help of pygame which is a very widely used library for making games with a very good graphical user interface.

Creating a basic display using pygame

First of all, we will be importing pygame in our code, it will help us in creating the game screen, exiting it, and updating it in case of any changes.

import pygame background = pygame.display.setmode((500, 350)) def function: while True: for i in pygame.event.get(): if i.type == pygame.QUIT: return pygame.display.update() function() pygame.quit()

This is the basics of any pygame project that includes :

  • pygame.display.setmode(): For defining the screen and its dimensions.
  • pygame.event.get(): For getting all the events that happen during the game.
  • pygame.Quit: Helps us quit the game if it’s not running.
  • pygame.display.update(): Will update the game according to the changes made.
  • pygame.quit(): To actually exit from the game.

Detecting mouse clicks in pygame

To detect the mouse click we just need to add a simple ‘if’ statement stating if the mouse button is clicked.

def function(): count = 0 while True: for i in pygame.event.get(): if i.type == pygame.QUIT: return #For detecting mouse click if i.type == pygame.MOUSEBUTTONDOWN: count += 1 print('clicked',count) pygame.display.update()

So in the function which was defined earlier, we just added an event that states that if the mouse is pressed then “clicked” is supposed to print on the output screen; Along with that, we have also defined a variable named “count” which will keep a count of how many time the mouse has been clicked.

Output :

Suppose the mouse was clicked 4 times so the output will look something like this.

clicked 1 clicked 2 clicked 3 clicked 4

Thus we have detected mouse clicks in Python using pygame.

Источник

Оцените статью