我正在创建一个程序,让我可以使用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
我看到了你要执行的操作,但是只有直接在源代码中输入的文件名(即“硬编码”或“字符串文字”)才需要使用“ 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')
当我尝试上面的代码时,这就是我得到的
tkinter.TclError: Invalid column index headings
。很好,这意味着第一个错误已解决。现在,您需要匹配要加载到显示器的文件。但这是一个不同的问题。
好的。再次感谢。