GUI应用程序在Spyder和cmd中运行,但不是作为独立的.exe运行

时间:2018-01-17 15:26:11

标签: python user-interface tkinter

我正在构建用于绘制数据的GUI应用程序。该程序在Spyder和命令提示符下运行良好,但在编译之后我注意到GUI打开,接受输入但是当我点击" Plot"按钮。相反,它意外关闭。我现在已经将代码简化为最小化,我认为我需要做我想做的事情。请参阅下面的代码。 我正在使用cx_Freeze来创建我的可执行程序。设置文件的代码也包含在下面。 任何帮助将非常感激。 感谢。

import tkinter as tk
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
from matplotlib.figure import Figure

class DataPlotter:
    def __init__(self,master):   

        master.geometry('300x100+200+100')
        master.title('Data Plotter')
        master.resizable(False,False)

        def PlotFigure(self,fig):
            self.Window = tk.Toplevel(master)                    
            self.canvas = FigureCanvasTkAgg(fig, self.Window)
            self.canvas.show()
            self.frametool = tk.Frame(self.Window)
            self.toolbar = NavigationToolbar2TkAgg(self.canvas,self.frametool)
            self.toolbar.update()
            self.frametool.pack(side=tk.TOP, fill=tk.BOTH)
            self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
            self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        def Run(self): #       
            try:
                app = Plotter(x=range(0,10), y=range(0,10))
                PlotFigure(self,app.plotting())
            except Exception as ex:
                messagebox.showinfo('Caught Error','Exception caught: ' + str(ex))
        ttk.Button(master, text='Plot', command=lambda:Run(self)).pack(anchor='center') 

class Plotter(object):
    def __init__(self, x=None, y=None):
        self.x = x
        self.y = y

    def plotting(self):
        fig = Figure()
        ax = fig.add_subplot(111)
        ax.plot(self.x, self.y, 'o-')
        return fig

def main():
    root = tk.Tk()
    root.grab_set()
    root.focus()
    DataPlotter(root)    
    root.mainloop()
if __name__ == "__main__": main()

以下设置文件:

from cx_Freeze import setup, Executable
import sys
import os
os.environ['TCL_LIBRARY'] = r'C:\ProgramData\Anaconda3\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\ProgramData\Anaconda3\tcl\tk8.6'

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

executables = [Executable('Data_Plotter.py', base=base)]

build_exe_options = {"packages": ["os","tkinter","numpy","matplotlib"]}

setup(
    name = "Data_Plotter",
    options = {"build_exe": build_exe_options},
    version = "1.0",
    description = "This program plots data and displays the graph in a new window",
    executables = executables
)

0 个答案:

没有答案