Tkinter从内存中删除存储的文件

时间:2018-03-09 00:02:22

标签: python-2.7 tkinter

    from Tkinter import *
    import Tkinter as tk
    import ttk
    import tkFileDialog
    import numpy as np
    import matplotlib
    matplotlib.use("TkAgg")
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
    from matplotlib.figure import Figure

    class Look():
        def __init__(self, master):
            self.master = master
            self.master.title("Demo")
            self.master.configure(background = "grey91") #the color will be changed later
            self.master.minsize(500, 300) # width + height
            self.master.resizable(False, False)

            self.top_frame = ttk.Frame(self.master, padding = (10, 10))
            self.top_frame.pack()

            ttk.Button(self.top_frame, text = "Load file", command = self.load_file,
               style = "TButton").pack()

            ttk.Button(self.top_frame, text = "Reset", command = self.clear_file,
                   style = "TButton").pack()

            ttk.Button(self.top_frame, text = "Plot", command = self.plot_file,
                              style = "TButton").pack()

            self.bottom_frame = ttk.Frame(self.master, padding = (10, 10))
            self.bottom_frame.pack()

            self.fig = plt.figure(figsize=(12, 5), dpi=100) ##create a figure; modify the size here
            self.fig.add_subplot()

            plt.title("blah")

            self.canvas = FigureCanvasTkAgg(self.fig, master = self.bottom_frame)
            self.canvas.show()
            self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

            self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.bottom_frame)
            self.toolbar.update()
            self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        def load_file(self):
            self.file =  tkFileDialog.askopenfilename(defaultextension = ".txt", filetypes = [("Text Documents", "*.txt")])

        def clear_file(self):
            self.fig.clf()
            self.fig.add_subplot()

            plt.xticks()
            plt.yticks()

            self.canvas.draw()


        def plot_file(self):
            self.r, self.g = np.loadtxt(self.file).transpose()
            self.fig.clf()
            plt.plot(self.r, self.g)
            self.canvas.show()


    def main():
        root = Tk()
        GUI = Look(root)
        root.mainloop()

    if __name__ == "__main__": main()

上面的代码创建了一个程序有三个按钮。加载文件按钮加载一个txt文件,重置按钮应该清除图并删除刚加载到内存中的文件。 Plot按钮用于将图形绘制到下面的画布上。

我有一个关于如何编写与Reset函数相关的函数的问题,即clear_file函数。目前它所做的只是清除画布上的情节。但似乎已加载到绘图的文件存储在内存中,因为再次单击Plot,它将显示绘图。我的目标是使用“重置”按钮使其重新开始 - 没有任何内存存储在内存中。我知道加载新文件会覆盖以前的文件。但是当有多个按钮用于加载不同的文件时,情况可能会变得复杂。因此,我希望Reset可以完成这项工作。 如果你想尝试这个小程序,你可以创建一个简单的txt,其中包含两个要加载到程序中的列数据。

感谢。

1 个答案:

答案 0 :(得分:1)

我会进行2次更改。将设置绘图的代码移动到自己的方法中,并在每次调用方法时重置帧。这可以通过破坏帧并重新构建它来完成。第二次更改我会更改重置命令以引用此新方法。

考虑到你的代码,我将改变以重置绘图。

import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

class Look():
    def __init__(self, master):
        self.master = master
        self.master.title("Demo")
        self.master.configure(background = "grey91") #the color will be changed later
        self.master.minsize(500, 300) # width + height
        self.master.resizable(False, False)

        self.top_frame = ttk.Frame(self.master, padding = (10, 10))
        self.top_frame.pack()

        ttk.Button(self.top_frame, text = "Load file", command = self.load_file,style = "TButton").pack()
        ttk.Button(self.top_frame, text = "Reset", command = self.new_plot,style = "TButton").pack()
        ttk.Button(self.top_frame, text = "Plot", command = self.plot_file,style = "TButton").pack()

        self.bottom_frame = ttk.Frame(self.master, padding = (10, 10))
        self.bottom_frame.pack()

        self.new_plot()

    # this function will reset your plot with a fresh one.
    def new_plot(self):
        self.bottom_frame.destroy()
        self.bottom_frame = ttk.Frame(self.master, padding = (10, 10))
        self.bottom_frame.pack()
        self.fig = plt.figure(figsize=(12, 5), dpi=100) ##create a figure; modify the size here
        self.fig.add_subplot()
        plt.title("blah")
        self.canvas = FigureCanvasTkAgg(self.fig, master = self.bottom_frame)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.bottom_frame)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def load_file(self):
        self.file =  filedialog.askopenfilename(defaultextension = ".txt", filetypes = [("Text Documents", "*.txt")])

    def clear_file(self):
        self.fig.clf()
        self.fig.add_subplot()

        plt.xticks()
        plt.yticks()

        self.canvas.draw()


    def plot_file(self):
        self.r, self.g = np.loadtxt(self.file).transpose()
        self.fig.clf()
        plt.plot(self.r, self.g)
        self.canvas.show()

if __name__ == "__main__":
    root = tk.Tk()
    GUI = Look(root)
    root.mainloop()