微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

matplotlib 和 tkinter,帮助删除旧图

如何解决matplotlib 和 tkinter,帮助删除旧图

所以我有一个简单的 tkinter GUI,我用它来帮助显示绘图。我有调用函数的按钮,如下面的 plot_record() 假设更新绘图。这一切正常,但是每当我关闭我的程序时,它需要一点时间来关闭。如果我经常更新绘图(例如 20 或 30 次),则需要很长时间才能关闭

我相信每当我更新旧图时,我都没有正确清除/关闭它们。以下函数的目标是删除之前的绘图内容并使用新数据进行更新。

我错过了什么吗?

import tkinter  as tk
from matplotlib.figure import figure
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (figureCanvasTkAgg,NavigationToolbar2Tk) 

import numpy as np
window = tk.Tk()
window.title("My Test Program")
def plot_record():
    for _ in range(0,5):
        #define base address in HRT for where recorder data is stored,hex values
        base = [0,800,1000,1800,2000,2800,3000,3800]
        #dummy data
        y=[]
        for i in range(0,10):
            y.append(1)
        for i in range(11,199):
            y.append(np.exp(-.01*(i-10))+np.random.rand()/10)
        
        fig3 = plt.figure(dpi=30)
        fig3.clear()
        plt.close(fig3)
        plot3 = fig3.add_subplot(1,1,1) 
        plot3.plot(y)
        plot3.set_xscale('linear')
        plot3.set_title('Recorder: ARC CHN'+str(0))
        # creating the Tkinter canvas containing the Matplotlib figure 
        canvas3 = figureCanvasTkAgg(fig3,frame4) 
        canvas3.draw()
        # placing the canvas on the Tkinter window 
        canvas3.get_tk_widget().grid(row=0,column=0,sticky='w')


#======================================================
#   FRAME 4
#======================================================
frame4 = tk.Frame(master=window,width=180,height=1000)
frame4.pack(fill=tk.Y,side=tk.LEFT)

#run plot once so that the plot will be above the button
plot_record();
# button that displays the plot 
arc_record = tk.Button(master = frame4,command = plot_record,height = 2,width = 20,bg="gray",fg="black",text = "Fetch ARC Trip Record") 

# place the buttons 
arc_record.grid(row=1,sticky='w')
#starts the loop which allows this program to execute commands/events
#based on the users inputs
window.mainloop()

更新:我已将我的代码更新为“最小可重现版本” 当你运行它时,你应该看到一个带有按钮的图。当您单击按钮时,它将更新绘图。请注意,我将此图嵌套在 for 循环中以帮助夸大我的观点。

  1. 如果您更新绘图一两次并关闭程序,它就会正常关闭
  2. 如果您将图更新 20 次以上,则程序需要更长的时间才能关闭

这似乎表明我的情节清除/关闭实际上并未清除或关闭情节,因此会留下一些伪影。有没有更好的方法来清理旧地块?

再次感谢:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。