运行 鼠标按下时循环

run a loop while mouse is down

我有这个代码:

import pyautogui
from pynput.mouse import Listener
# import threading
import time

mouseIsDown = False

def on_click(*args):
    if args[-1]:
        if args[-2].name == "left":
            mouseIsDown = True
            print("down")

    elif not args[-1]:
        if args[-2].name == "left":
            mouseIsDown = False
            print("up")

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

while mouseIsDown:
    print("hello!")
    time.sleep(0.001)

它应该 运行 在按下鼠标按钮时每 .001 秒循环一次,但它什么也没做。

有什么建议吗?

运行 这个线程是非阻塞的,你可能需要这样的东西(Read it in document):

import pyautogui
from pynput.mouse import Listener
# import threading
import time

mouseIsDown = False

def on_click(*args):
    global mouseIsDown
    if args[-1]:
        if args[-2].name == "left":
            mouseIsDown = True
            print("down")

    elif not args[-1]:
        if args[-2].name == "left":
            mouseIsDown = False
            print("up")

listner = Listener(on_click=on_click)
listner.start()

while True:
    if mouseIsDown:
        time.sleep(0.5) # time to sleep
        print("hello!")