How to detect what button was clicked? (Pynput) - python

I'm trying to detect what mouse button was clicked
so here is my code:
from pynput.mouse import Listener
def on_click(button, pressed):
if button.Left and pressed:
print("You pressed the left mouse button")
if button.Right and pressed:
print("You pressed the right mouse button")
so there was no errors but It's not working any Ideas?

From the Documentation Here
CODE
from pynput import mouse
def on_move(x, y):
print('Pointer moved to {0}'.format(
(x, y)))
def on_click(x, y, button, pressed):
print(button) # Print button to see which button of mouse was pressed
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
# Collect events until released
with mouse.Listener(
on_click=on_click
) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(on_click=on_click)
listener.start()
As you can see, the button parameter in the function on_click tells you which button was pressed.
EDIT:
Here is how you may handle action based on which button of the mouse was pressed
def on_click(x, y, button, pressed):
btn = button.name
if btn == 'left':
print('Left if Pressed')
# ====== < Handle Pressed or released Event ====== > #
if pressed:
print('Do somethin when Pressed with LEft')
else:
print('LEFT is Released')
elif btn == 'right':
print('Right BTN was pressed ')
# ====== < Handle Pressed or released Event ====== > #
if not pressed:
print('right Button is released')
else:
pass

I post a second answer because of a different nature of the issue found on code here
The issue is how you call the imports.
CORRET CODE
from pynput import mouse
mouse_ = mouse.Controller()
button = mouse.Button
def on_click(x, y, button, pressed):
btn = button.name
if btn == 'left':
if pressed:
mouse_.click(button_.left)
print('works')
with mouse.Listener(
on_click=on_click
) as listener:
listener.join()
Copy and Paste the code without changes.
WARNING
when I use button.left my pc becomes extremely lagy so i suggest you to don't use is unless you know what you are doing

Related

How to block only one mouse button?

The middle button on my mouse sometimes clicks several times when I click it once. My mouse is expensive and I like it, so I decided to fix it with a program.
When I release the middle button, I'd like to freeze it for 0.1 seconds without freezing the other buttons.
I tried to block with the supress=True flag in pynput library, and then sending button for windows, but this doesn't work.
from pynput.mouse import Button, Controller, Listener
import time
mouse = Controller()
class BlockMiddle:
def __init__(self):
self.start = time.time()
with Listener(on_click=self.on_click, on_move=self.on_move,
suppress=True
) as listener:
listener.join()
def on_click(self, x, y, button, pressed):
if button == Button.left:
if pressed:
mouse.press(Button.left)
else:
mouse.release(Button.left)
if button == Button.right:
if pressed:
mouse.press(Button.right)
else:
mouse.release(Button.right)
if button == Button.middle:
if pressed:
if time.time() - self.start > 0.1:
mouse.press(Button.middle)
else:
mouse.release(Button.middle)
self.start = time.time()
if button == Button.x1:
if pressed:
mouse.press(Button.x1)
else:
mouse.release(Button.x1)
if button == Button.x2:
if pressed:
mouse.press(Button.x2)
else:
mouse.release(Button.x2)
def on_move(self, x, y):
mouse.position = (x, y)
block = BlockMiddle()
Finally I solved my problem.
from pynput.mouse import Button, Controller, Listener
import time
mouse = Controller()
class BlockMiddle:
def __init__(self):
self.start = time.time()
self.listener = Listener(
on_click=self.on_click,
on_move=self.on_move,
on_scroll=self.on_scroll,
suppress=False
)
with self.listener as l:
l.join()
def on_click(self, x, y, button, pressed):
self.listener._suppress = False
if not button == Button.middle:
return
if time.time() - self.start < 0.1:
self.listener._suppress = True
if not pressed:
self.start = time.time()
self.listener._suppress = False
def on_move(self, x, y):
self.listener._suppress = False
def on_scroll(self, x, y, dx, dy):
self.listener._suppress = False
block = BlockMiddle()

pynput.mouse Listener do not stop

Here is my prank code for my friend but I can not stop this program from keyboard when I make executable.
How can I stop this listener from keyboard shortcut. I know it is thread issue.
import sys
import pyautogui
import keyboard
from pynput.mouse import Listener
from threading import Thread
global x,y
def on_move(x, y):
print ("Mouse moved to ({0}, {1})".format(x, y))
def on_click(x, y, button, pressed):
try: #FOR AUTO FAIL-SAFE
if pressed:
print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
pyautogui.move(x+100,y+100)
except:
pass
def on_scroll(x, y, dx, dy):
print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
while True:
if keyboard.is_pressed("q"):
sys.exit(0)
break
So here is my fix. I works because I had the same problem:
Insert:
from pynput.keyboard import Key
then:
In on_move(), on_click(), and on_scroll() add:
if key == Key.f10:
sys.exit()
This will check that when you press f10 (or you can change), the program will exit
You also need to pass key as an argument!
The full updated code is:
import sys
import pyautogui
import keyboard
from pynput.keyboard import Key
from pynput.mouse import Listener
from threading import Thread
global x,y
def on_move(key, x, y):
print ("Mouse moved to ({0}, {1})".format(x, y))
if key == Key.f10:
sys.exit()
def on_click(key, x, y, button, pressed):
try: #FOR AUTO FAIL-SAFE
if pressed:
print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
pyautogui.move(x+100,y+100)
except:
pass
if key == Key.f10:
sys.exit()
def on_scroll(key, x, y, dx, dy):
print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
if key == Key.f10:
sys.exit()
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
while True:
if keyboard.is_pressed("q"):
sys.exit(0)
break
I solved this problem. When mouse position(x,y) on left-top and mid scrolled. Program finishes itself.
def on_scroll(x, y, dx, dy):
print('Scrolled {0} at {1}'.format(
'down' if dy < 0 else 'up',
(x, y,dx,dy)))
if x<100 and y<100:
return False

How can I make my program not run in an endless loop once my mouse button is pressed

So I'm trying to make the program not run in an endless loop once pressed is true and check for when the mouse button is released and stop the while loop.
from pynput import mouse
from pynput.mouse import Button, Controller
import time
m = Controller()
def on_click(x, y, button, pressed):
print('Pressed' if pressed else 'Released')
while (pressed):
m.move(0, 1)
time.sleep(.001)
with mouse.Listener(
on_click=on_click) as listener:
listener.join()
Something like this. Don't try to sleep for 1ms, you'll waste too many resources.
from pynput import mouse
from pynput.mouse import Button, Controller
import time
m = Controller()
mousedown = False
def on_click(x, y, button, pressed):
global mousedown
print('Pressed' if pressed else 'Released')
mousedown = pressed
listener = mouse.Listener(on_click=on_click)
while True:
if mousedown:
m.move( 0, 1 )
time.sleep( 0.1 )

How does "with mouse.Listener" work in pynput?

I'm trying to understand an example from the pynput documentation.
I understand the general gist, that the code prints a message when the mouse moves/is clicked/etc. I'm just confused about how it does so.
def on_click(x, y, button, pressed):
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
if not pressed:
# Stop listener
return False
with mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as listener:
listener.join()

Python: Recording Keystrokes and Mousemovement simultaneously

i cant find a solution for the following problem:
I would like to record keystrokes and mousemovement at the same time. Right now i tried to combine the scripts from the pynput Package Documentation.
Monitoring the mouse: https://pynput.readthedocs.io/en/latest/mouse.html#monitoring-the-mouse
Monitoring the keyboard:
https://pynput.readthedocs.io/en/latest/keyboard.html#monitoring-the-keyboard
from pynput import mouse
from pynput import keyboard
def on_move(x, y):
print('Pointer moved to {0}'.format(
(x, y)))
def on_click(x, y, button, pressed):
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
if not pressed:
# Stop listener
return False
def on_scroll(x, y, dx, dy):
print('Scrolled {0}'.format(
(x, y)))
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as listener:
listener.join()
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Right now the keyboard listener only starts after the mouse listener gets closed. Is there any way to record mouse and keyboard at the same time? Are there better site-packages for this? Thanks a lot in advance!
All you need is this, my friend
# Collect events until released
with keyboard.Listener(on_release=on_release) as k_listener, mouse.Listener(on_click=on_click) as m_listener:
k_listener.join()
m_listener.join()

Categories

Resources