如何在Tkinter的Treeview小部件中開啟Excel電子表格?
Excel電子表格包含一組以行和列形式儲存的資訊。我們可以使用**Treeview**小部件在Tkinter應用程式中顯示和使用電子表格資料。Tkinter中的Treeview小部件幫助使用者以表格形式新增和操作資料。但是,為了分析和操作大量資料,Python提供了**Pandas**庫,該庫提供了許多內建函式和方法來執行資料分析。
在本例中,我們將按照以下步驟在Tkinter中顯示Excel資料:
匯入所需的庫,例如**Numpy、Pandas**和**filedialog**。
新增選單欄,以提示使用者從資源管理器中開啟檔案。
新增命令並定義函式**open_file()**,使其只接受資源管理器中的**.xlsx**檔案。
建立一個**Treeview**小部件。
透過將列資料轉換為列表,在**Treeview**小部件中新增列。
迭代列以查詢給定資料中的所有標題。
可以透過將給定資料幀轉換為NumPy物件來識別行。轉換後,我們可以使用列表方法將其轉換為列表。
迭代所有行,並將行按順序插入樹中。
示例
# Import the required libraries from tkinter import * from tkinter import ttk, filedialog import numpy import pandas as pd # Create an instance of tkinter frame win = Tk() # Set the size of the tkinter window win.geometry("700x350") # Create an object of Style widget style = ttk.Style() style.theme_use('clam') # Create a Frame frame = Frame(win) frame.pack(pady=20) # Define a function for opening the file def open_file(): filename = filedialog.askopenfilename(title="Open a File", filetype=(("xlxs files", ".*xlsx"), ("All Files", "*."))) if filename: try: filename = r"{}".format(filename) df = pd.read_excel(filename) except ValueError: label.config(text="File could not be opened") except FileNotFoundError: label.config(text="File Not Found") # Clear all the previous data in tree clear_treeview() # Add new data in Treeview widget tree["column"] = list(df.columns) tree["show"] = "headings" # For Headings iterate over the columns for col in tree["column"]: tree.heading(col, text=col) # Put Data in Rows df_rows = df.to_numpy().tolist() for row in df_rows: tree.insert("", "end", values=row) tree.pack() # Clear the Treeview Widget def clear_treeview(): tree.delete(*tree.get_children()) # Create a Treeview widget tree = ttk.Treeview(frame) # Add a Menu m = Menu(win) win.config(menu=m) # Add Menu Dropdown file_menu = Menu(m, tearoff=False) m.add_cascade(label="Menu", menu=file_menu) file_menu.add_command(label="Open Spreadsheet", command=open_file) # Add a Label widget to display the file content label = Label(win, text='') label.pack(pady=20) win.mainloop()
輸出
如果執行上述程式碼,它將顯示一個視窗,該視窗頂部包含一個選單,用於開啟Excel檔案。
開啟檔案後,它將顯示視窗中的電子表格資料。
廣告