在 python 包 matplotlib 中通过按钮或鼠标单击使程序暂停

Make the program pause by button or mouse click in python package matplotlib

通过程序界面按钮或鼠标点击让程序暂停,再次点击按钮或鼠标让程序从上次停止的地方继续,重点是暂停如何achieve.The 从最后一次暂停开始的时间是 uncertain.My 代码如下:

import matplotlib.pyplot as plt
class ab():
    def __init__(self,x,y):
        self.x=x
        self.y=y
a=ab(2,4)
b=ab(2,6)
c=ab(2,8)
d=ab(6,10)
f=ab(6,13)
e=ab(6,15)
task=[]
task.append(a)
task.append(b)
task.append(c)
task.append(d)
task.append(e)
task.append(f)
for i in task:
    while i.x<=30:
        print(i.x)
        plt.plot(i.x,i.y,'o')
        plt.pause(0.1)
        i.x=i.x+2
        i.y=i.y+2

plt.show()

您可以组合 matplotlib's animation module with matplotlib's event connections。下面的代码应该或多或少地做你想做的:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# I'm replacing your class with two lists for simplicity
x = [2,2,2,6,6,6]
y = [4,6,8,10,13,15]

# Set up the figure
fig, ax = plt.subplots()
point, = ax.plot(x[0],y[0],'o')

# Make sure all your points will be shown on the axes
ax.set_xlim(0,15)
ax.set_ylim(0,15)

# This function will be used to modify the position of your point
def update(i):
    point.set_xdata(x[i])
    point.set_ydata(y[i])
    return point

# This function will toggle pause on mouse click events
def on_click(event):
    if anim.running:
        anim.event_source.stop()
    else:
        anim.event_source.start()
    anim.running ^= True

npoints = len(x)

# This creates the animation
anim = FuncAnimation(fig, update, npoints, interval=100)
anim.running=True

# Here we tell matplotlib to call on_click if the mouse is pressed
cid = fig.canvas.mpl_connect('button_press_event', on_click)

# Finally, show the figure
plt.show()