【问题标题】:Use while loop inside pynput's mouse listener在 pynput 的鼠标监听器中使用 while 循环
【发布时间】:2021-05-05 06:09:42
【问题描述】:

即使我松开鼠标左键,while 循环也会返回 true,这会使按下 = false。我不知道如何跳出循环来更新按下的值。

from pynput import keyboard
from pynput import mouse
from pynput.mouse import Button, Controller

control = Controller()

def on_click(x, y, button, pressed):
    if button == mouse.Button.left:
        while pressed == True:
            print(pressed)

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

有什么方法可以更新循环,让它知道什么时候按下 = false。

【问题讨论】:

  • 不要使用while 循环,而是正常使用if not pressed。当您运行while 循环时,它不能再次运行on_click 并且它不能停止这个循环。如果你真的需要在循环中运行一些代码,那么在单独的线程中运行它。

标签: python while-loop mouselistener pynput mouse-listeners


【解决方案1】:

如果你真的需要运行一些循环,那么你必须在分隔的 thread 中执行它,因为如果你在 on_click 中运行它,那么你会阻止 listener 并且它不能运行另一个 on_click

on_click 应该在thread 中开始循环,并使用全局变量来控制何时停止。

from pynput import mouse
from pynput.mouse import Button, Controller
import threading

control = Controller()

running = False

def process():
    print('start')
    count = 0
    while running:
        print(count)
        count += 1
    print('stop')
    
def on_click(x, y, button, pressed):
    global running # to assing value to global variable (instead of local variable)
    
    if button == mouse.Button.left: 
        if pressed:
            if not running:  # to run only one `process`
                running = True
                threading.Thread(target=process).start()
        else:
            running = False

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

【讨论】:

  • 感激不尽。如果不是你,我会被困在这个问题上很长时间!
  • @PorpoisesUnited 那么我只想问你为什么不接受它作为答案:) 这真的很有帮助..
猜你喜欢
  • 2019-12-28
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多