我想使用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或线程的内部工作原理不够熟悉,无法确定其原因。
plt.show(block=False)
和plt.pause(sec)
可以结合使用。 - M.T