Warm tip: This article is reproduced from serverfault.com, please click

Passing file from filedialogue to another function tkinter

发布于 2020-11-29 00:12:06

I am creating a program that let me visualise my csv file with tkinter. However, I am not able to read the file I grab with the filedialogue. I also have tried to pass filename as argument to the file_loader that as well does not work. I still found myself with a FileNotFoundError: [Errno 2] No such file or directory: '' error.

root =Tk()

root.geometry("500x500") 
root.pack_propagate(False) # tells the root to not let the widgets inside it determine its size.
root.resizable(False, False) 

frame = tk.LabelFrame(root, text="CSV/Excel")
frame.place(height=250, width=500)

# Frame for open file dialog
file_frame = tk.LabelFrame(root, text="Opened file")
file_frame.place(height=100, width=400, rely=0.65, relx=0.1)

# Buttons
browse_butt = tk.Button(file_frame, text="Browse A File", command=lambda: file_picker())
browse_butt.place(rely=0.65, relx=0.50)

load_butt = tk.Button(file_frame, text="Load File", command=lambda: file_loader())
load_butt.place(rely=0.65, relx=0.30)

# The file/file path text
label_file = ttk.Label(file_frame, text="Nothing Selected")
label_file.place(x=0, y=0)

 # initialising the treeView
 trv = ttk.Treeview(frame)
 trv.place(relheight=1, relwidth=1)

#============================= Functions under buttons ================================

def file_picker():
    root.filename = filedialog.askopenfilename()
    label_file["text"] = root.filename
    return None

def file_loader():
    Label_path=label_file["text"]

    try:
       csv_file= r''.format(Label_path)
       df= pd.read_csv(csv_file)

    except ValueError:
       messagebox.showerror('File Format Error', 'This program can only read a csv')
    
    return None
      
    clear_data()
    trv['column']=list(df.columns)
    trv['display']="headings"

    for column in trv['column']:
       trv.heading(column, text=column)
    
    df_rows=df.to_numpy().to_list()

    for row in df_rows:
        trv.insert('', 'end', values=row)

    def clear_data():
        trv.delete(*trv.get_children())

    return None
    
Questioner
Camue
Viewed
11
Novel 2020-11-29 08:19:10

I see what you were trying to do, but the 'r' is only needed for filenames that you directly enter in the source code (aka "hardcoded" or "string literals"). Here you can use the file path directly from the label.

def file_loader():
    try:
       csv_file= label_file["text"]
       df= pd.read_csv(csv_file)

    except ValueError:
       messagebox.showerror('File Format Error', 'This program can only read a csv')