首页 > 解决方案 > 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, column=0, sticky='w')
#starts the loop which allows this program to execute commands/events
#based on the users inputs
window.mainloop()

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

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

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

再次感谢 :)

标签: pythonmatplotlibtkintertkinter-canvas

解决方案


推荐阅读