使用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()
相关推荐
yue0082 分钟前
C# 生成指定位数的编号
开发语言·c#
大笨象、小笨熊6 分钟前
Qt Widgets和Qt Quick在开发工控触摸程序的选择
开发语言·qt
红黑色的圣西罗19 分钟前
C# List.Sort方法总结
开发语言·c#
E_ICEBLUE1 小时前
Python 教程:如何快速在 PDF 中添加水印(文字、图片)
开发语言·python·pdf
我爱学习_zwj1 小时前
服务器接收用户注册信息教程
python
大连滚呢王1 小时前
Linux(麒麟)服务器离线安装单机Milvus向量库
linux·python·milvus·银河麒麟·milvus_cli
南方的狮子先生1 小时前
【C++】C++文件读写
java·开发语言·数据结构·c++·算法·1024程序员节
Alex艾力的IT数字空间1 小时前
完整事务性能瓶颈分析案例:支付系统事务雪崩优化
开发语言·数据结构·数据库·分布式·算法·中间件·php
m0_738120721 小时前
网络安全编程——基于Python实现的SSH通信(Windows执行)
python·tcp/ip·安全·web安全·网络安全·ssh