PYTHON 仅在按住鼠标右键时执行代码

问题描述 投票:0回答:1

有没有办法只在按住

Mouse button right
时执行python代码?如果
Mouse right
变为 up,代码应立即中断。

我尝试使用

pynput
库,但
pressed
参数在 while 循环上不起作用。它可以在没有
while
循环的情况下正常工作:在鼠标右键向下和鼠标右键向上事件上打印正确的消息。但是使用 while 循环,它会开始无限循环,并且当鼠标按钮向上变为向上时不会停止。

任何解决方案都值得赞赏,而不仅仅是 pynput 库。

        from pynput import mouse

        def on_click(x, y, button, pressed):
            if button == mouse.Button.right:
                if pressed:
                    print(pressed)
                    while pressed:  # Makes the problem
                        print("Executing code...") # Endless Print here. Even if Mouse button right becomes Up
              
                else:
                    print(pressed)

        listener = mouse.Listener(on_click=on_click)
        listener.start()
        listener.join()
        
python python-3.x
1个回答
0
投票

即使在鼠标右键单击后,代码仍然无限期地打印的原因是 because

while
循环。

当您在

start()
上调用
listener
时,您就开始循环,以便它可以继续检查输入。通过您的功能,它能够获得右键单击。但是,当它检测到右键单击时,它会运行您的
while
循环。

以下是

while
循环的工作原理。正如您在示例中所看到的,要停止 while 循环,您需要在其中添加代码来更改它正在检查的值或使用
break
。在您的情况下,由于输入检测已经是一个 while 循环,因此您不需要使用另一个循环。

这是固定代码:

from pynput import mouse

held = False #Variable to change when held.

#If you've tested pynput, you'll know that everytime you right click it will count it as
#two clicks, one on click and one on release. Because of this, we can change this variable
#to `True` after the first click and `False` after the second one.

def on_click(x, y, button, pressed):
    global held #call global to get the variable `held` from inside a function
    if button == mouse.Button.right:
        if held:
            held = False
        else:
            held = True

    else: print('No Right Click Detected')

    if held:
        print('Executing code…') #code to execute when variable `held` is `True`

listener = mouse.Listener(on_click=on_click) #Pass your function to the listener's while loop
listener.start()
listener.join()
© www.soinside.com 2019 - 2024. All rights reserved.