สเปรดชีต Excel มีชุดข้อมูลที่จัดเก็บในรูปแบบของแถวและคอลัมน์ เราสามารถแสดงและใช้ข้อมูลสเปรดชีตในแอปพลิเคชัน Tkinter โดยใช้ Treeview วิดเจ็ต วิดเจ็ต Treeview ใน Tkinter ช่วยให้ผู้ใช้สามารถเพิ่มและจัดการข้อมูลในรูปแบบของตาราง อย่างไรก็ตาม เพื่อวิเคราะห์และจัดการชุดข้อมูลขนาดใหญ่ Python ได้จัดเตรียม Pandas ไลบรารีซึ่งให้การเข้าถึงฟังก์ชันและวิธีการมากมายในการวิเคราะห์ข้อมูล
สำหรับตัวอย่างนี้ เราจะทำตามขั้นตอนเหล่านี้เพื่อแสดงข้อมูล Excel ใน Tkinter
-
นำเข้าไลบรารีที่จำเป็น เช่น Numpy, Pandas, และ กล่องโต้ตอบ .
-
เพิ่มแถบเมนูเพื่อขอให้ผู้ใช้เปิดไฟล์จาก Explorer
-
เพิ่มคำสั่งและกำหนดฟังก์ชัน 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

เมื่อเราเปิดไฟล์ จะแสดงข้อมูลสเปรดชีตในหน้าต่าง
