Tkinter program closes automatically without error after closing message box

343 Views Asked by At

I created a tkinter GUI to allow a user to select csv files and generate graphs using matplotlib. This program works well from my IDE, but closes after creating one graph in my frozen executable (cx_freeze). The exe runs without error - it brings up the graph in the default photo editor then displays a popup with the chart's file path. When the popup (tx.messagebox) is closed, the main window also closes and the program has to be rerun.

The desired behavior is for the main window to stay open, allowing the user to generate additional graphs. Below is a stripped down version of my code. Does anyone know what could be triggering the main window to close after accepting the messagebox?

from pathlib import Path
from tkinter import Tk
from tkinter import Frame
from tkinter import Button
from tkinter import filedialog
import tkinter.messagebox as messagebox
import os
import traceback
import matplotlib.pyplot as plt

class graphing_program(Tk):
    def __init__(self,*args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
        self.window_width   = 300
        self.window_height  = 150
        self.geometry(f"{str(self.window_width)}x{str(self.window_height + 20)}+300+300")
        container = Frame(self)
        container.place(width=self.window_width,height=self.window_height)
        self.wm_title('Graphing Program')
        self.button = Button(self, text="Select Files",
                            command= self.open_file)
        self.button.place(relwidth = 1,relheight = 1,relx=0,rely=0)
        #%% Variables
        self.data_dir = Path('.')
  
    def open_file(self):
        try:
            temp_files = filedialog.askopenfilenames(initialdir = self.data_dir,title = "Select File",filetypes = (("csv","*.csv"),("all files","*.*")))
            savefn = lp.plot_data(temp_files)
            os.startfile(savefn)
            messagebox.showinfo('Chart Generated',f'Chart Path:\n\t{savefn}')
        except:traceback.print_exc();raise

class lp():
    def plot_data(file_paths):
        savefn = Path('./example_graph.png')
        x = [1,2,3,4,5,6,7,8,9,10]
        y = [1,2,3,4,5,6,7,8,9,10]
        fig1 =  plt.figure(figsize=[7.5,10]) 
        plt.plot(x,y,'-',color = 'r')
        fig1.savefig(fname= savefn,format="png")
        plt.close(fig1)
        return(savefn)          

if __name__ == "__main__":
    app = graphing_program()
    app.mainloop()
0

There are 0 best solutions below