2
votes

i am using PyMouse(Event) for detecting if mouse button is pressed:

from pymouse import PyMouseEvent

class DetectMouseClick(PyMouseEvent):
    def __init__(self):
        PyMouseEvent.__init__(self)

    def click(self, x, y, button, press):
        if button == 1:
            if press:
                print("click")
        else:
            self.stop()

O = DetectMouseClick()
O.run()

This works so far, but now i want to loop print("click") until mouse isnt pressed anymore ... i tried:

def click(self, x, y, button, press):
    if button == 1:
        if press:
            do = 1
            while do == 1:
                print("down")
                if not press:
                    do = 0

And also smth. like:

while press:
    print("click")

Someone can help me? Thanks!

1
I don't think you can, as the mouse itself is not sending a constant stream of 'clicks' when you press down the button. This is a mechanical 'problem', not software-related. EDIT: you should try using a joystick instead ;) - Oli

1 Answers

3
votes

I think as Oli points out in his comment there isn't a constant stream of clicks when the mouse button is held down so you'll have to have the print in a loop. Having the while loop running on the same thread prevents the click event firing when the mouse is released so the only way I can think of to achieve what you are after is to print("click") from a separate thread.

I'm not a Python programmer but I've had a stab which works on my machine (Python 2.7 on Windows 8.1):

from pymouse import PyMouseEvent
from threading import Thread

class DetectMouseClick(PyMouseEvent):
    def __init__(self):
        PyMouseEvent.__init__(self)

    def print_message(self):
        while self.do == 1:
            print("click")

    def click(self, x, y, button, press):
        if button == 1:
            if press:
                print("click")
                self.do = 1
                self.thread = Thread(target = self.print_message)
                self.thread.start()
            else:
                self.do = 0
                print("end")
        else:
            self.do = 0
            self.stop()

O = DetectMouseClick()
O.run()