2

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

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

当我运行这段代码时,我的电脑变得非常慢。我是初学者。我需要使用带有普通代码的侦听器。谢谢

4

1 回答 1

1

请记住,该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()

于 2020-07-16T01:18:18.493 回答