Python 3.x 收集鼠标事件

Python 3.x Collecting Mouse Events

我只是想学习“监听器”功能。但是我无法通过单击鼠标来打破任何循环。这是一个例子:

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 函数被调用了两次。按下鼠标按钮时一次,释放按钮时再次。由于该函数将被调用两次,我们不能通过使用鼠标按钮状态的不同值再次调用它来打破第一次函数调用创建的循环。

我假设您的意图是在按住鼠标按钮时每秒打印一次计数器。我在下面为您提供了一个片段,它使用线程来完成此操作,并且每次调用 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()