使用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()
相关推荐
feixing_fx5 小时前
第一个 JS 程序:在浏览器控制台和 Node 中分别运行
开发语言·前端·javascript·前端框架·ecmascript
Evand J5 小时前
【MATLAB例程】二维IMM-UKF定位,基于四个基站的AOA与测距辅助
开发语言·matlab
feixing_fx6 小时前
变量与声明:let、const、var 的选择边界
开发语言·前端·javascript·前端框架
岁月宁静6 小时前
五、《从零手撸 Agent》 — 什么是 Agent:从“会聊天”到“会做事”,差的就是一个循环
python·agent
个 人 练 习 生7 小时前
C++:从零基础到深入了解vector的使用
开发语言·c++·经验分享·学习·程序人生·stl
梯度下降者7 小时前
Python - 函数
python·高阶函数·可调用对象·functools·嵌套作用域
H.莓飛7 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
hudd6688 小时前
JavaEE 初阶 - 文件操作和IO
java·开发语言·java-ee
starzy19909 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
wuyk55510 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎