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

python-将文件从文件对话传递到另一个函数tkinter

(python - Passing file from filedialogue to another function tkinter)

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

我正在创建一个程序,让我可以使用tkinter可视化我的csv文件。但是,我无法读取使用抓取的文件filedialogue我也尝试过将filename作为参数传递给file_loader那也不起作用。我仍然发现自己有FileNotFoundError: [Errno 2] No such file or directory: ''错误。

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
0
Novel 2020-11-29 08:19:10

我看到了你要执行的操作,但是只有直接在源代码中输入的文件名(即“硬编码”或“字符串文字”)才需要使用“ r”。在这里,你可以直接从标签使用文件路径。

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')