使用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()
相关推荐
CodeCipher5 分钟前
Java基础复习之继承
java·开发语言
BillKu12 分钟前
Java延时
java·开发语言
雨师@32 分钟前
ATM 模拟器 Golang 程序--示例
开发语言·后端·golang
向上的车轮1 小时前
语言特性适用的场景:卫星、火箭控制系统用什么开发语言?
java·开发语言·c++·c#·c·ada
Allen Bright1 小时前
【JS-2】JavaScript基础语法完全指南:从入门到精通
开发语言·javascript·ecmascript
云边小网安3 小时前
java集合(十) ---- LinkedList 类
java·开发语言·青少年编程·java集合
Zephyrtoria4 小时前
区间合并:区间合并问题
java·开发语言·数据结构·算法
你怎么知道我是队长5 小时前
GO语言---匿名函数
开发语言·后端·golang
lansye5 小时前
侃侃AI编程
开发语言·qt·ai编程
2501_915374356 小时前
LangChain自动化工作流实战教程:从任务编排到智能决策
python·langchain·自动化