我想使用matplotlib和pynput近乎实时地绘制鼠标的移动,但我怀疑我的代码被阻塞了。代码使用的是this answer的简化版本。
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或线程的内部工作原理不够熟悉,无法确定原因是什么。
发布于 2018-05-29 06:38:53
将带有GUI输入的线程与matplotlib GUI并行运行可能会导致问题。
在任何情况下,只使用matplotlib工具可能更有意义。有一个可用的event handling mechanism,它提供了一个用于获取当前鼠标位置的"motion_notify_event"
。为该事件注册的回调将存储鼠标位置并对更新点进行blit。
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()
https://stackoverflow.com/questions/50505550
复制相似问题