簡體   English   中英

將文件從文件對話框傳遞到另一個 function tkinter

[英]Passing file from filedialogue to another function tkinter

我正在創建一個程序,讓我使用 tkinter 可視化我的 csv 文件。 但是,我無法讀取使用filedialogue抓取的文件。 我還嘗試將文件名作為參數傳遞給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
    

我知道您要做什么,但是僅在您直接在源代碼中輸入的文件名(也稱為“硬編碼”或“字符串文字”)中才需要“r”。 這里可以直接使用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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM