使用askopenfilename

时间:2017-07-28 17:48:51

标签: python user-interface tkinter data-analysis

我正在尝试使用用户友好的数据检索程序。我创建了一个简单的GUI,当用户点击“文件”时 - > “新” - >浏览文件。他们应该能够在GUI中打开.multi文件。所有按钮都工作,文件浏览器打开以搜索文件,但是在选择.multi文件并打开后没有任何反应。我没有收到错误代码,我不知道刚刚打开的文件发生了什么。

我想要发生的是.multi文件在GUI中获取'保存/存储'(我不确定这是否是正确的语法)。然后,当用户从“脚本” - >“浏览”(也在GUI内)导入脚本时,脚本将解析刚导入的文件并绘制脚本中设置的任何参数。

我的问题是这样的:当我打开文件时会发生什么?如何让它保存/存储在GUI中,直到脚本可以解析数据?

这是我的代码:

from tkinter import *
import tkinter as tk
from tkinter import ttk, filedialog, Toplevel
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror 

LARGE_FONT= ("Verdana", 12)
NORM_FONT= ("Verdana", 10)
SMALL_FONT= ("Verdana", 8)
plt.style.use("dark_background")
plt.style.use("seaborn-bright")

def popupmsg(msg):
    popup = tk.Toplevel()
    popup.wm_title("Menu")
    label = ttk.Label(popup, text=msg, font=NORM_FONT)
    label.pack(side="top", fill="x", pady=10)
    B1 = ttk.Button(popup, text="Okay", command = popup.destroy)
    B1.pack()
    popup.mainloop()

这就是我认为问题所在,因为我不确定我的文件是否实际加载,因为我没有收到错误代码或任何已加载的指示。

def load_file(self):
    fname = askopenfilename(filetypes=(("All files", "*.*"),
                                           ('Python files', '*.py*'),
                                           ('Multi files', '*.multi*')))

class PyWinProject(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.wm_title(self, "TkGraph")


        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        menubar = tk.Menu(container)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="New", command = lambda: load_file(self))
        filemenu.add_command(label="Add", command = lambda: popupmsg("This is not yet supported"))
        filemenu.add_command(label="Exit", command=quit)
        menubar.add_cascade(label="File", menu=filemenu)
        tk.Tk.config(self, menu=menubar)

        scriptmenu = tk.Menu(menubar, tearoff=0)
        scriptmenu.add_command(label="Browse", command = lambda: load_file(self))
        menubar.add_cascade(label="Script", menu=scriptmenu)
        tk.Tk.config(self, menu=menubar)

        parameter = tk.Menu(menubar, tearoff=0)
        parameter.add_command(label="Selection", command = lambda: popupmsg("This is not yet supported"))
        menubar.add_cascade(label="Parameter", menu=parameter)
        tk.Tk.config(self, menu=menubar)

        timemenu = tk.Menu(menubar, tearoff=0)
        timemenu.add_command(label="Selection", command = lambda: popupmsg("This is not yet supported"))
        menubar.add_cascade(label="Time", menu=timemenu)
        tk.Tk.config(self, menu=menubar)

        self.frames = {}
        for F in (StartPage, PageOne):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
            self.show_frame(StartPage)
            def show_frame(self, cont):
                frame = self.frames[cont]
                frame.tkraise()

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Home", font=LARGE_FONT)
        label.pack(pady=10,padx=10)
        button1 = ttk.Button(self, text="Graph",
                             command=lambda: controller.show_frame(PageOne))
        button1.pack()

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Graph", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = ttk.Button(self, text="Back to Home",
                             command=lambda: controller.show_frame(StartPage))
        button1.pack()
        fig = plt.figure()
        canvas = FigureCanvasTkAgg(fig, self)
        canvas.show()

        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

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

app = PyWinProject()
app.mainloop()

****更新:我已在def load_file(self):

之后将此行添加到我的代码中
 if fname:
        try:
            fname.open()
        except:                     
            showerror("Open Source File", "Failed to read file\n'%s'" % fname)
        return 

然后按预期返回:“无法读取文件”。那么为什么python不能读取文件呢?

这是python的完整错误报告:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\.......\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "<ipython-input-34-3810935f52b9>", line 68, in <lambda>
    filemenu.add_command(label="New", command = lambda: load_file(self))
  File "<ipython-input-34-3810935f52b9>", line 52, in load_file
    return fname.open()
AttributeError: 'str' object has no attribute 'open'

0 个答案:

没有答案