未检测到滚动 - Pynput

Scrolling is not detected - Pynput

from pynput.mouse import Listener
from pynput.keyboard import Key, Listener
xy = []
sizes = []
isCtrl = False

size = 11

def on_scroll(x, y, dx, dy):
    global size, sizes
    global isCtrl
    print(isCtrl)
    if isCtrl:
        size += dy
        sizes.append(size)
        print(sizes[-1])
def on_press(key):
    global isCtrl
    if key == Key.ctrl:
        isCtrl = True
    print(isCtrl)
def on_release(key):
    global isCtrl
    if key == Key.ctrl:
        isCtrl = False
    print(isCtrl)

# Collect events until released
with Listener(on_scroll=on_scroll,
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

这就是代码。我真的不确定我的滚动代码为什么以及如何工作,因为即使我已经滚动了也没有调用该函数。感谢高级解决方案!

一些错误:

  1. 你导入了Listener两次,键盘监听覆盖了鼠标监听
  2. 键盘侦听器没有 on_press 方法。

考虑到你想同时监控鼠标和keyboard.You需要创建两个线程来监听them.Maybe你需要:

from pynput.mouse import Listener as mouseListener
from pynput.keyboard import Key, Listener as keyboardListener

xy = []
sizes = []
isCtrl = False

size = 11


def on_scroll(x, y, dx, dy):
    global size, sizes
    global isCtrl
    print(isCtrl)
    if isCtrl:
        size += dy
        sizes.append(size)
        print(sizes[-1])


def on_press(key):
    global isCtrl
    if key == Key.ctrl:
        isCtrl = True
    print(isCtrl)


def on_release(key):
    global isCtrl
    if key == Key.ctrl:
        isCtrl = False
    print(isCtrl)


# Mouse listener
mouse_listener = mouseListener(on_scroll=on_scroll)
mouse_listener.start()

# Keyboard listener
with keyboardListener(on_press=on_press, on_release=on_release) as listener:
    listener.join()