matplotlib 在循环中销毁FigureCanvasTkAgg

vwoqyblh  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(130)

我尝试在一个循环中删除一个嵌入在tkinter中的matplotlib图形,并且每隔2秒就会被另一个matplotlib图形替换,但是这些图形不是逐个删除,而是一个接一个地叠加在一起,并且在循环结束时才会全部删除。

root = tk.Tk()
root.geometry("600x500")

fig, ax = plt.subplots(nrows = 3, ncols = 1, figsize = (6, 4))
t = np.linspace(0,10,len(X_EEG1[0]))
for data1, data2, data3, datay in zip(X_EEG1_ten, X_EEG2_ten, X_EMG_ten, y_ten):
    ax[0].plot(t, data1, color = 'w', lw = 0.5)
    ax[1].plot(t, data2, color = 'w', lw = 0.5)
    ax[2].plot(t, data3, color = 'grey', lw = 0.5)
    plt.tight_layout()

    canvas = FigureCanvasTkAgg(fig, master = root)  
    canvas.draw()
    canvas.get_tk_widget().pack()
    
    root.update() # updating window to show figure
    time.sleep(2) # wait 2 seconds

    canvas.get_tk_widget().destroy() # destroy figure
    root.update() # updating window to show destroyed figure

root.mainloop()

任何帮助都很感激,谢谢。

j13ufse2

j13ufse21#

我想出来了!👍🏻

root = tk.Tk()
root.geometry("600x500")

plt.style.use('dark_background')
fig, ax = plt.subplots(nrows = 3, ncols = 1, figsize = (6, 4))
t = np.linspace(0,10,len(X_EEG1[0]))
ax0, = ax[0].plot(t, X_EEG1_ten[0], color = 'w', lw = 0.5)
ax1, = ax[1].plot(t, X_EEG2_ten[0], color = 'w', lw = 0.5)
ax2, = ax[2].plot(t, X_EMG_ten[0], color = 'grey', lw = 0.5)
for data1, data2, data3, datay in zip(X_EEG1_ten, X_EEG2_ten, X_EMG_ten, y_ten):
    ax0.set_xdata(t)
    ax0.set_ydata(data1)
    ax1.set_xdata(t)
    ax1.set_ydata(data2)
    ax2.set_xdata(t)
    ax2.set_ydata(data3)
    plt.tight_layout()

    canvas = FigureCanvasTkAgg(fig, master = root)  
    canvas.get_tk_widget().grid(row=0,column=0)
    canvas.draw()
    root.update()
    canvas.flush_events() # critical missing piece here!
    time.sleep(2)

root.mainloop()

相关问题