Python3.x收集鼠标事件

Python3.x收集鼠标事件,python,python-3.x,mouselistener,Python,Python 3.x,Mouselistener,我只是想学习“侦听器”的功能。但我无法用鼠标点击打破任何循环。以下是一个例子: from pynput.mouse import Listener import time def on_click(x, y, button, pressed): counter = 0 while True: print(counter) counter += 1 time.sleep(1) if pressed:

我只是想学习“侦听器”的功能。但我无法用鼠标点击打破任何循环。以下是一个例子:

from pynput.mouse import Listener
import time

def on_click(x, y, button, pressed):
    counter = 0
    while True:
        print(counter)
        counter += 1
        time.sleep(1)
        if pressed:
            break

with Listener(on_click = on_click) as listener:
    listener.join()
当我运行这段代码时,我的电脑变得非常慢。我是初学者。我需要使用正常代码的侦听器。
谢谢

请记住,单击函数会调用两次。按下鼠标按钮一次,松开按钮一次。由于该函数将被调用两次,我们不能通过使用鼠标按钮状态的不同值再次调用它来打破第一次函数调用创建的循环

我假设你的意图是每按住鼠标键一秒钟打印一次计数器。我在下面为您提供了一个代码片段,它使用线程来完成这一任务,每次调用on_click函数都可以读取鼠标的状态以及用于打印的线程的状态

在函数中使用
time.sleep()
时,它会导致调用它的线程休眠。当您只有一个线程在运行时,它会导致整个程序每秒休眠一次。我相信您的计算机没有滞后,但是鼠标会出现滞后,因为您的输入被每秒的睡眠呼叫中断

from pynput import mouse
import time
from threading import Thread

def on_click(x, y, button, pressed):
    thread = Thread(target = threaded_function)
    if pressed and thread.is_alive() == False: 
        thread.start()
    if not pressed:
        if thread.is_alive():
            thread.join()
        return False

def threaded_function():
    count = 0
    while True:
        count+=1
        print(count)
        time.sleep(1)

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