Can a python class contain a method to delete itslef?

91 views Asked by At

I am coding a tkinter class for data manipulation. I would like to find a way to delete the object by clicking on a button, exactly like the X button to quit a window.
Here is what my interface looks like:

tkinter interface

The main window is a class that contains the matplotlib plot and general controls.
Each of the three "widgets" on the right are objects of a class that contains a dataframe from loaded csv file and some specific controls like the choice of x-axis and y-axis variable.

I want the X button to make the widget and all it contains disappear and also make the plot disappear from the master object (I assume this part have to be done manually).
Here is the initialization of the Widget class and the definition of the controls:

class Data_Widget():
    """ This Class creates the main window with the curve plot and general buttons like open files, Clear all, Plot all.
    
    Arguments:
    -master: the parent window, automatically the PlotWindow class
    -data: data loaded into the widget self.data used to plot the curve
    -filepath: the filepath of the loaded data
    -color: color of the curve
    
    methods:
    -create_widget_controls : create the controls (buttons...)
    -set_widget_color : set the color of the associated curve
    -set_x_var and set_y_var : set the x and y var of the plotted curve
    -master_plot : gives the order of plotting the curve to the master class (PlotWindow) (method plot_widget)
    -master_clear_plot : gives the order of clearing the plot to the master class (PlotWindow) (method clear_widget_plots)
    -delete_widget : delete the widget
    -create_exportload_popup : export the data contained in the widget as CSV file.
                Used where widget has been created by selecting data from another widget with PlotWindow multiple selection method
    """
    def __init__(self, master, data = pd.DataFrame(), filepath='Nothing loaded', x_var=None, y_var= None, color="blue"):
        super().__init__()
        self.master = master
        # Create variables for data and plot
        self.widget_id=0                            #id of the widget   
        self.filepath=filepath                      #filepath of the loaded data
        self.data = data                            #dataframe loaded into the widget
        self.selected_data = pd.DataFrame()         #data selected by the user
        self.x_var = x_var                          #x variable of the plotted curve
        self.y_var = y_var                          #y variable of the plotted curve
        self.color = color                          #color of the plotted curve
        self.create_widget_controls()               #create the controls (buttons...)

    def __del__(self):
        print ("Object gets destroyed")

    def create_widget_controls(self):
        self.widget_frame = tk.Frame(self.master.scrollable_widgets_frame)
        self.widget_frame.pack(side=tk.TOP, fill=None, expand=False)

        empty_space = tk.Label(self.widget_frame, text="")
        empty_space.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.filename_label = tk.Label(self.widget_frame, text="-------------- " + os.path.basename(self.filepath) + " --------------")
        self.filename_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.x_label = tk.Label(self.widget_frame, text="X axis variable")
        self.x_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        self.x_var_dropdown_label = tk.StringVar()
        self.x_var_dropdown = tk.OptionMenu(self.widget_frame, self.x_var_dropdown_label, "")
        self.x_var_dropdown.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.y_label = tk.Label(self.widget_frame, text="Y axis variable")
        self.y_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        self.y_var_dropdown_label = tk.StringVar()
        self.y_var_dropdown = tk.OptionMenu(self.widget_frame, self.y_var_dropdown_label, "")
        self.y_var_dropdown.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.plot_button = tk.Button(self.widget_frame, text="Plot", command=self.master_plot)
        self.plot_button.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.clear_button = tk.Button(self.widget_frame, text="Clear", command=self.master_clear_plot)
        self.clear_button.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.color_button = tk.Button(self.widget_frame, text="color", bg=self.color, fg="white", command=self.set_widget_color)
        self.color_button.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.exportload_button = tk.Button(self.widget_frame, text="Export plotted\ncurve as csv", command=self.create_exportload_popup)
        self.exportload_button.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=1)

        self.delete_button = tk.Button(self.widget_frame, text="X", command=self.destroy_widget)
        self.delete_button.pack(side=tk.BOTTOM, anchor=tk.NE)


        # Load the widget with the data from given by the load function of PlotWindow()
        self.x_var_dropdown['menu'].delete(0, 'end')
        self.y_var_dropdown['menu'].delete(0, 'end')
        for col in self.data.columns:
            self.x_var_dropdown['menu'].add_command(label=col, command=lambda var=col: self.set_x_var(var))
            self.y_var_dropdown['menu'].add_command(label=col, command=lambda var=col: self.set_y_var(var))

        if self.master.auto_plot.get() == 1:
            self.master_plot()
        
        # self.x_var_dropdown.bind('<<OptionMenuSelect>>', self.plot)
        # self.y_var_dropdown.bind('<<OptionMenuSelect>>', self.plot)
    
    def destroy_widget(self):
        self.widget_frame.destroy()

For now the function destroy_widget only makes the frame disappear but it's only visual and all the data is still there.
I wrote a def__del__(self) that should be used to delete the object from outside but I can't figure how to use it do delete the object from within itself.

0

There are 0 answers