pynput.mouse听者不停

pynput.mouse Listener do not stop

这是我给我朋友的恶作剧代码,但是当我制作可执行文件时我无法通过键盘停止这个程序。

如何通过键盘快捷方式停止此侦听器。我知道这是线程问题。

import sys
import pyautogui
import keyboard
from pynput.mouse import Listener
from threading import Thread

global x,y

def on_move(x, y):
    print ("Mouse moved to ({0}, {1})".format(x, y))

def on_click(x, y, button, pressed):
    try: #FOR AUTO FAIL-SAFE
        if pressed:
            print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
            pyautogui.move(x+100,y+100)
    except:
        pass

def on_scroll(x, y, dx, dy):
    print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))


with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()

while True:
    if keyboard.is_pressed("q"):
        sys.exit(0)
        break

这是我的解决方法。我工作是因为我遇到了同样的问题: 插入:

from pynput.keyboard import Key

然后: 在 on_move()、on_click() 和 on_scroll() 中添加:

if key == Key.f10:
    sys.exit()

这将检查当您按 f10(或者您可以更改)时,程序将退出

您还需要将密钥作为参数传递!

完整的更新代码是:

import sys
import pyautogui
import keyboard
from pynput.keyboard import Key
from pynput.mouse import Listener
from threading import Thread

global x,y

def on_move(key, x, y):
    print ("Mouse moved to ({0}, {1})".format(x, y))
    if key == Key.f10:
        sys.exit()

def on_click(key, x, y, button, pressed):
    try: #FOR AUTO FAIL-SAFE
        if pressed:
            print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
            pyautogui.move(x+100,y+100)
    except:
        pass
    if key == Key.f10:
        sys.exit()

def on_scroll(key, x, y, dx, dy):
    print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
    if key == Key.f10:
        sys.exit()


with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()

while True:
    if keyboard.is_pressed("q"):
        sys.exit(0)
        break

我解决了这个问题。当左上角和中间的鼠标位置(x,y)滚动时。程序自己完成。

def on_scroll(x, y, dx, dy):
    print('Scrolled {0} at {1}'.format(
    'down' if dy < 0 else 'up',
    (x, y,dx,dy)))
    if x<100 and y<100:
        return False