【问题标题】:run a loop while mouse is down鼠标按下时运行循环
【发布时间】:2021-08-05 15:38:14
【问题描述】:

我有这个代码:

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)

它应该在鼠标按钮按下时每 0.001 秒运行一次循环,但它完全没有做任何事情。

有什么建议吗?

【问题讨论】:

    标签: python loops pyautogui pynput


    【解决方案1】:

    以非阻塞方式运行这个线程,你可能需要这样的东西(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!")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多