1

我创建了一个 tkinter GUI 以允许用户选择 csv 文件并使用 matplotlib 生成图形。该程序在我的 IDE 中运行良好,但在我的冻结可执行文件 (cx_freeze) 中创建一个图形后关闭。exe 运行没有错误 - 它会在默认照片编辑器中显示图表,然后显示带有图表文件路径的弹出窗口。当弹出窗口(tx.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()
4

0 回答 0