使用tkinter拖入excel文件并显示

使用tkinter拖入excel文件并显示

  • 效果
  • 代码

效果

代码

python 复制代码
import tkinter as tk
from tkinter import ttk
from tkinterdnd2 import TkinterDnD, DND_FILES
import pandas as pd


class ExcelViewerApp(TkinterDnD.Tk):
    def __init__(self):
        super().__init__()
        self.title("Excel Viewer")
        self.geometry("800x600")

        self.drop_label = ttk.Label(self, text="Drag and drop an Excel file here")
        self.drop_label.pack(pady=20)

        self.tree = ttk.Treeview(self)
        self.tree.pack(expand=True, fill='both')

        self.drop_target_register(DND_FILES)
        self.dnd_bind('<<Drop>>', self.drop)

    def drop(self, event):
        file_path = event.data.strip('{}')
        if file_path.endswith(('.xls', '.xlsx')):
            self.show_excel(file_path)
        else:
            self.drop_label.config(text="Please drop a valid Excel file")

    def show_excel(self, file_path):
        df = pd.read_excel(file_path)
        self.tree.delete(*self.tree.get_children())
        self.tree["columns"] = list(df.columns)
        self.tree["show"] = "headings"

        for column in self.tree["columns"]:
            self.tree.heading(column, text=column)

        for index, row in df.iterrows():
            self.tree.insert("", "end", values=list(row))

        self.drop_label.config(text="Drag and drop an Excel file here")


if __name__ == "__main__":
    app = ExcelViewerApp()
    app.mainloop()
相关推荐
爱上电路设计3 小时前
有趣的算法
开发语言·c++·算法
studyForMokey3 小时前
kotlin 函数类型接口lambda写法
android·开发语言·kotlin
2401_858120264 小时前
探索sklearn文本向量化:从词袋到深度学习的转变
开发语言·python·机器学习
与墨学长5 小时前
Rust破界:前端革新与Vite重构的深度透视(中)
开发语言·前端·rust·前端框架·wasm
虫小宝5 小时前
Java中的软件架构重构与升级策略
java·开发语言·重构
bigbearxyz5 小时前
Java实现图片的垂直方向拼接
java·windows·python
CTGU_daffodil6 小时前
matlab 绘制高等数学中的二维函数示例
开发语言·matlab
立秋67896 小时前
使用Python绘制堆积柱形图
开发语言·python
逸群不凡6 小时前
C++|哈希应用->布隆过滤器
开发语言·数据结构·c++·算法·哈希算法
jOkerSdl6 小时前
第三十章 方法大全(Python)
python