2

我试图在按下鼠标按钮时保存鼠标的 x 和 y 坐标,并且在松开鼠标按钮时分别保存。我可以打印它们,但无法将它们保存到变量中。

这是我得到的:

from pynput.mouse import Listener

def on_click(x, y, button, pressed):
    print('{0} at {1}'.format(
        'Pressed' if pressed else 'Released',
        (x, y)))
    if not pressed:
        # Stop listener
        return False

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

然后我将如何在全局范围内调用这些变量以与另一个模块一起使用(例如 pyautogui?)

4

2 回答 2

3

你已经准备好了所有的东西,所以我只需要添加几行。Globals 不是最好做事方式,但由于这个程序不是太复杂,他们会完成这项工作。

down_x 等的初始值并不重要,因为它们会被覆盖,但它们必须存在,否则 Python 会抛出错误。

#if you want to delay between mouse clicking, uncomment the line below
#import time
from pynput.mouse import Listener
import pyautogui

down_x = down_y = up_x = up_y = -1

def on_click(x, y, button, pressed):
    global down_x
    global down_y
    global up_x
    global up_y
    if pressed:
        (down_x, down_y) = (x, y)
    else:
        (up_x, up_y) = (x, y)
        return False

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

print("Mouse drag from", down_x, ",", down_y, "to", up_x, ",", up_y)

# you may wish to import the time module to make a delay
#time.sleep(1)
pyautogui.mouseDown(down_x, down_y)
#time.sleep(1)
pyautogui.mouseUp(up_x, up_y)
于 2019-08-08T06:02:59.850 回答
0

使用全局变量:

from pynput.mouse import Listener

xx, yy = 0, 0

def on_click(x, y, button, pressed):
    global xx, yy
    xx, yy = x, y
    print('{0} at {1}'.format(
        'Pressed' if pressed else 'Released',
        (x, y)))
    if not pressed:
        # Stop listener
        return False

with Listener(on_click=on_click) as listener:
    listener.join()
    # here you can read xx and yy

如果您的代码变得更复杂,您可以考虑将其封装在一个类中。

于 2018-07-20T06:52:09.243 回答