为什么存储在函数中的鼠标位置在函数外没有改变?

Why is the mouse position that is stored in the function not changed outside the function?

我目前正在 python 从事棋盘项目。我需要在按下时存储鼠标位置,以查看 (x, y) 坐标是否接触到一块。

如果是,棋子的坐标将与鼠标的坐标相同,直到松开鼠标。我想制作棋子跟着鼠标的效果

然后,当它被释放时,我想存储它被释放的位置的坐标以便与这些一起使用。 我听说过 pynput 并安装了它,但我还是个新手。

这不在我的主文件中,但它试图在单击时获取鼠标的位置:

from pynput import mouse


mx, my = 0, 0


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


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

print(str(mx) + str(my))

我不太明白这个模块背后的逻辑。我在网上找到了代码,并尝试将值存储在变量中,但显然行不通。

要将值存储在外部变量中,您必须使用 global

但通常所有的代码都在on_click里面执行,就没有必要使用global


from pynput import mouse

pressed_x = 0
pressed_y = 0

released_x = 0
released_y = 0

is_pressed = False
is_released = False

def on_click(x, y, button, pressed):
    global pressed_x
    global pressed_y

    global released_x
    global released_y

    global is_pressed
    global is_released

    # store in external variables
    if pressed:
        is_pressed = True
        pressed_x = x
        pressed_y = y
        #print('LISTENER: pressed:', pressed_x, pressed_y)
    else:        
        is_released = True
        released_x = x
        released_y = y
        #print('LISTENER: released:', released_x, released_y)

    #if not pressed:
    #    # Stop listener
    #    return False

# --- main ---

# start listener at the beginning
listener = mouse.Listener(on_click=on_click)
listener.start()

# use variables in your code
while True:
    if is_pressed:
        print('RUN: pressed:', pressed_x, pressed_y)
        is_pressed = False
    if is_released:
        print('RUN: released:', released_x, released_y)
        is_released = False

# stop listener at the end
listener.stop()            
listener.join()

print('END: pressed:', pressed_x, pressed_y)
print('END: released:', released_x, released_y)

但是如果您使用 pygamepyglet 或任何 GUI 框架(tkinterPyQTPySidewxPythonPyGTK, Kivy, 等) 那么他们有自己的方法来获取鼠标位置 (bind(), signals, events, 等) 并且没有必要使用 pynput.