Simulate Mouse Clicks on Python

62,475

Solution 1

python-uinput is very easy to use.

http://tjjr.fi/software/python-uinput/

Here's an example https://github.com/tuomasjjrasanen/python-uinput/blob/master/examples/mouse.py

Solution 2

You can use PyMouse which has now merged with PyUserInput. I installed it via pip:

  1. apt-get install python-pip

  2. pip install pymouse

In some cases it used the cursor and in others it simulated mouse events without the cursor.

from pymouse import PyMouse

m = PyMouse()
m.position() #gets mouse current position coordinates
m.move(x,y)
m.click(x,y) #the third argument "1" represents the mouse button
m.press(x,y) #mouse button press
m.release(x,y) #mouse button release

You can also specify which mouse button you want used. Ex left button:

m.click(x,y,1)

Keep in mind, on Linux it requires Xlib.

Solution 3

PyAutoGui works superb.. Thanks to Al Sweigart...

An example of mine...

import pyautogui

pyautogui.FAILSAFE = False

for x in range(555, 899):
    pyautogui.moveTo(x, x)

Solution 4

The evdev package provides bindings to parts of the input handling subsystem in Linux. It also happens to include a pythonic interface to uinput.

Example of sending a relative motion event and a left mouse click with evdev:

from evdev import UInput, ecodes as e

capabilities = {
    e.EV_REL : (e.REL_X, e.REL_Y), 
    e.EV_KEY : (e.BTN_LEFT, e.BTN_RIGHT),
}

with UInput(capabilities) as ui:
    ui.write(e.EV_REL, e.REL_X, 10)
    ui.write(e.EV_REL, e.REL_Y, 10)
    ui.write(e.EV_KEY, e.BTN_LEFT, 1)
    ui.syn()

Solution 5

You can try to interface XTE program from the Python script.

Share:
62,475
dbdii407
Author by

dbdii407

Updated on December 23, 2021

Comments

  • dbdii407
    dbdii407 over 2 years

    I'm currently in the process of making my Nintendo Wiimote (Kinda sad actually) to work with my computer as a mouse. I've managed to make the nunchuk's stick control actually move the mouse up and down, left and right on the screen! This was so exciting. Now I'm stuck.

    I want to left/right click on things via python when I press A, When I went to do a search, All it came up with was tkinter?

    So my question is, What do I call to make python left/right click on the desktop, and if it's possible, maybe provide a snippet?

    Thank you for your help!

    NOTE: I guess I forgot to mention that this is for Linux.

  • Jewenile
    Jewenile almost 7 years
    Any idea how to do such tasks without using external libraries/tools?
  • oleskii
    oleskii over 5 years
    @Jewenile, you can manipulate linux uinput kernel module directly. You can see python-uinput source to get an idea how it may be implemented. github.com/tuomasjjrasanen/python-uinput
  • Mihai.Mehe
    Mihai.Mehe over 2 years
    Pymouse ModuleNotFoundError: No module named unix Try installing pynput
  • Tiago Rangel de Sousa
    Tiago Rangel de Sousa about 2 years
    Thanks! Works perfect