使用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()
相关推荐
CTA量化套保2 小时前
最新量化表达入门,从概念规则到简单实现
人工智能·python
大不点wow2 小时前
Java序列化与反序列化:让对象走出JVM
java·开发语言·jvm
阿里嘎多学长2 小时前
2026-07-22 GitHub 热点项目精选
开发语言·程序员·github·代码托管
吃饱了得干活3 小时前
别再手动解析 LLM 输出了!LangChain 四种结构化输出方案对比
后端·python·langchain
噢,我明白了3 小时前
Java中日期和字符串的处理
java·开发语言·日期
爱刷碗的苏泓舒3 小时前
C 语言 if-else 与 switch-case 分支语句对比
c语言·开发语言
ikun_文3 小时前
Python进阶—函数编程
python·pycharm
MC皮蛋侠客3 小时前
uv 系列(三):依赖、锁文件与环境同步——可重复构建的核心
python·uv
量化吞吐机3 小时前
2026年交易想法转Python,中间先补规则转译
人工智能·python
-银雾鸢尾-3 小时前
C#中的泛型约束
开发语言·c#