鼠标左键按下时如何执行?

How do I perform a while left mouse is down?

我正在尝试 运行 一个 while 循环,直到松开鼠标按钮。

我试过用 pynput 做这样的事情

from pynput.mouse import Listener

mouse = False

# This function will be called when any key of mouse is pressed
def on_click(*args):
    # see what argument is passed.
    print(args)
    if args[-1] and args[-2].name == 'left':
        print('The "{}" mouse key has held down'.format(args[-2].name))
        mouse = True
        while mouse:
            # Do stuff

    elif not args[-1] and args[-2].name == 'left':
        print('The "{}" mouse key is released'.format(args[-2].name))
        mouse = False

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

但它从未停止。 有什么办法可以等待鼠标松开事件吗? 在 while 循环中加入某种条件,例如

while mouse_down:
    # Do stuff until the mouse is released

我也试过 python 鼠标库,但它只是出乎意料。 基本上我想要一个 while 循环到 运行 每次我按下鼠标左键 直到 我释放它。 这可能吗?

这是您的代码版本,它不断循环,监控 mouse 变量。

from pynput.mouse import Listener

mouse = False

def on_click(*args):
    global mouse
    if args[-1] and args[-2].name == 'left':
        mouse = True
    elif not args[-1] and args[-2].name == 'left':
        mouse = False

with Listener(on_click=on_click) as listener:
    while True:
        if mouse:
            print("Doing stuff while the mouse is down...")

这是一个使用 threading.Event 而不是轮询的版本。

from pynput.mouse import Listener
from threading import Event

event = Event()

def on_click(*args):
    if args[-1] and args[-2].name == 'left':
        event.set()
    elif not args[-1] and args[-2].name == 'left':
        event.clear()

with Listener(on_click=on_click) as listener:
    while event.wait():
        print("Doing stuff while the mouse is down....")

这些版本都没有正常退出,但我对 pynput.mouse 还不够熟悉,无法解决这个问题。