使用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()
相关推荐
鸡鸭扣24 分钟前
Docker:3、在VSCode上安装并运行python程序或JavaScript程序
运维·vscode·python·docker·容器·js
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑1 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
我真不会起名字啊2 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
神秘_博士2 小时前
自制AirTag,支持安卓/鸿蒙/PC/Home Assistant,无需拥有iPhone
arm开发·python·物联网·flutter·docker·gitee
laimaxgg2 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
水瓶丫头站住2 小时前
Qt的QStackedWidget样式设置
开发语言·qt
Moutai码农3 小时前
机器学习-生命周期
人工智能·python·机器学习·数据挖掘
小钊(求职中)3 小时前
Java开发实习面试笔试题(含答案)
java·开发语言·spring boot·spring·面试·tomcat·maven
小白教程4 小时前
python学习笔记,python处理 Excel、Word、PPT 以及邮件自动化办公
python·python学习·python安装