Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

python - Print while mouse pressed

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...