首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >绘图鼠标移动Python

绘图鼠标移动Python
EN

Stack Overflow用户
提问于 2018-05-24 17:20:04
回答 1查看 2.3K关注 0票数 9

我想使用matplotlib和pynput近乎实时地绘制鼠标的移动,但我怀疑我的代码被阻塞了。代码使用的是this answer的简化版本。

代码语言:javascript
复制
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或线程的内部工作原理不够熟悉,无法确定原因是什么。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-29 06:38:53

将带有GUI输入的线程与matplotlib GUI并行运行可能会导致问题。

在任何情况下,只使用matplotlib工具可能更有意义。有一个可用的event handling mechanism,它提供了一个用于获取当前鼠标位置的"motion_notify_event"。为该事件注册的回调将存储鼠标位置并对更新点进行blit。

代码语言:javascript
复制
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()
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50505550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档