Python绘制鼠标移动轨迹

9

我想使用matplotlib和pynput实时绘制鼠标的移动轨迹,但是我怀疑代码被阻塞了。代码使用了这个答案的简化版本。

import matplotlib.pyplot as plt
from pynput import mouse
from time import sleep

fig, ax = plt.subplots()

ax.set_xlim(0, 1920-1)
ax.set_ylim(0, 1080-1)
plt.show(False)
plt.draw()

x,y = [0,0]
points = ax.plot(x, y, 'o')[0]
# cache the background
background = fig.canvas.copy_from_bbox(ax.bbox)

def on_move(x, y):
    points.set_data(x,y)
    # restore background
    fig.canvas.restore_region(background)
    # redraw just the points
    ax.draw_artist(points)
    # fill in the axes rectangle
    fig.canvas.blit(ax.bbox)

with mouse.Listener(on_move=on_move) as listener:
    sleep(10)

这段代码似乎在ax.draw_artist(points)处停止执行。pynput鼠标监听器是一个threading.Thread,所有回调函数都从该线程中调用。我对matplotlib或线程的内部工作原理不够熟悉,无法确定其原因。

1个回答

10

同时运行具有GUI输入的线程可能会导致问题,与matplotlib GUI并行运行。无论如何,仅使用matplotlib工具可能更有意义。有一个事件处理机制可用,提供一个"motion_notify_event"来获取当前鼠标位置。注册此事件的回调将存储鼠标位置并更新点。

import matplotlib.pyplot as plt


fig, ax = plt.subplots()

ax.set_xlim(0, 1920-1)
ax.set_ylim(0, 1080-1)

x,y = [0], [0]
# create empty plot
points, = ax.plot([], [], 'o')

# cache the background
background = fig.canvas.copy_from_bbox(ax.bbox)

def on_move(event):
    # append event's data to lists
    x.append(event.xdata)
    y.append(event.ydata)
    # update plot's data  
    points.set_data(x,y)
    # restore background
    fig.canvas.restore_region(background)
    # redraw just the points
    ax.draw_artist(points)
    # fill in the axes rectangle
    fig.canvas.blit(ax.bbox)


fig.canvas.mpl_connect("motion_notify_event", on_move)
plt.show()

有趣的是,我之前并不知道这个可能性。对于任何想在绘图后设定一定时间关闭图形或在绘图过程中运行某些代码的人来说,plt.show(block=False)plt.pause(sec) 可以结合使用。 - M.T

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接