我的matplotlib脚本在Windows上运行,运行两个动画:
anim = []
anim.append( matplotlib.animation.FuncAnimation(fig_ul, updatePlots_ul,frames=None, interval=100, repeat=True) )
anim.append( matplotlib.animation.FuncAnimation(fig_dl, updatePlots_dl, frames=None,interval=100, repeat=True) )
plt.show() # line 476
当我通过关闭其中一个数字来终止脚本时,我得到一个例外:
Traceback (most recent call last):
File "tcpClient.py", line 476, in <module>
plt.show()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\matplotlib\pyplot.py", line 253, in show
return _show(*args, **kw)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\matplotlib\backend_bases.py", line 163, in __call__
manager.show()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 610, in show
self.canvas.manager.window.attributes('-topmost', 1)
AttributeError: 'NoneType' object has no attribute 'attributes'
如何改进我的代码以避免这种不整洁的异常?
更新:添加最低限度,可验证的示例
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation
def _updateSubplot(sc):
i_data = [1,2]
q_data = [1,2]
sc.set_offsets(np.c_[i_data, q_data])
# Create figure A and subplots
fig_A, axarr_A = plt.subplots(nrows=2, ncols=2, figsize=(10, 6))
x_data = []
y_data = []
sc_A_1 = axarr_A[0,0].scatter(x_data, y_data, c='r', s=4)
sc_A_2 = axarr_A[0,1].scatter(x_data, y_data, c='r', s=4)
sc_A_5 = axarr_A[1,0].scatter(x_data, y_data, c='r', s=4)
sc_A_6 = axarr_A[1,1].scatter(x_data, y_data, c='r', s=4)
fig_A.tight_layout()
# Create figure B and subplots
fig_B, axarr_B = plt.subplots(nrows=2, ncols=1, figsize=(3, 6))
x_data = []
y_data = []
sc_B_1 = axarr_B[0].scatter(x_data, y_data, c='r', s=4)
sc_B_2 = axarr_B[1].scatter(x_data, y_data, c='r', s=4)
fig_B.tight_layout()
# Animation functions
def updatePlots_A(i):
_updateSubplot(sc_A_1)
def updatePlots_B(i):
_updateSubplot(sc_B_1)
_updateSubplot(sc_B_2)
anim = [] # List of Animation objects for tracking
anim.append( matplotlib.animation.FuncAnimation(fig_A, updatePlots_A, frames=None, interval=100, repeat=True) )
anim.append( matplotlib.animation.FuncAnimation(fig_B, updatePlots_B, frames=None, interval=100, repeat=True) )
plt.show()