You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter如何将浏览获取的Excel路径读取为pandas DataFrame

可直接运行的修改后代码

from tkinter import *
from tkinter import filedialog, messagebox
import pandas as pd
import smtplib

# 全局变量存储两个Excel文件路径
file_path_2a = ""
file_path_pr = ""

def browseFiles():
    global file_path_2a
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "选择2A对应的Excel文件",
                                          filetypes = (("Excel文件",
                                                        "*.xlsx *.xls"),
                                                       ("所有文件",
                                                        "*.*")))
    if filename:
        file_path_2a = filename
        label_file_explorer.configure(text="2A文件已选择: "+filename)

def browseFiles1():
    global file_path_pr
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "选择PR对应的Excel文件",
                                          filetypes = (("Excel文件",
                                                        "*.xlsx *.xls"),
                                                       ("所有文件",
                                                        "*.*")))
    if filename:
        file_path_pr = filename
        label_file_explorer.configure(text="PR文件已选择: "+filename)


def save_slogan():
    global file_path_2a, file_path_pr
    # 校验两个文件是否都已选择
    if not file_path_2a or not file_path_pr:
        messagebox.showerror("错误", "请先选择两个Excel文件")
        return
    # 读取两个Excel文件
    df1 = pd.read_excel(file_path_2a)
    df2 = pd.read_excel(file_path_pr)
    xx1 = df1.rename(columns={"Description":"Desc 2A","Doc Number":"Document Number"})
    xx = df2.rename(columns={"Description":"Desc PR","Doc Number":"Document Number"})
    combined = pd.merge(xx1, xx, how="outer", on="Document Number")
    def case_code(row): 
        if row["Tax Amount 2A"] == row["Tax Amount PR"]:
            return "exact"
        elif pd.isna(row["Tax Amount 2A"]):
            return "Addition in PR"
        elif pd.isna(row["Tax Amount PR"]):
            return "Addition in 2A"
        elif row["Tax Amount 2A"] != row["Tax Amount PR"]:
            return "mismatch"

    codes = combined.apply(case_code, axis="columns")
    answer = combined.assign(**{"Match type": codes})
    final = answer[["Match type"] + [*combined.columns]] 
    final.to_excel('done1.xlsx', index=False)
    messagebox.showinfo("完成", "文件已处理并保存为done1.xlsx")     


# 创建主窗口
window = Tk()
window.title('PR与2A比对工具')
window.geometry("500x500")
window.config(background = "white")

# 创建提示标签
label_file_explorer = Label(window,
                            text = "请先选择两个Excel文件再执行处理",
                            width = 100, height = 4,
                            fg = "blue")


button_explore = Button(window,
                        text = "Browse File 2A",
                        command = browseFiles)
button_explore1 = Button(window,
                        text = "Browse File PR",
                        command = browseFiles1)
button_explore2 = Button(window,
                        text = "Go and Save",
                        command = save_slogan)

# 布局组件
label_file_explorer.grid(column = 1, row = 1)
button_explore.grid(column = 1, row = 2)
button_explore1.grid(column=1, row=3)
button_explore2.grid(column=1,row=4)

window.mainloop()

核心修改说明

  • 新增两个全局变量存储两个选中的Excel文件路径,实现路径在不同函数间的传递
  • 将文件选择器的过滤规则调整为仅优先显示Excel格式文件,避免选错文件类型
  • 修正了原代码中save_slogan函数的缩进错误,将所有处理逻辑纳入函数作用域
  • 补全了df1、df2的读取逻辑,使用pd.read_excel()读取选中路径对应的Excel文件
  • 修复了原代码中merge、apply行多余的右括号语法错误
  • 新增了文件选择校验和处理完成提示,提升使用体验
  • 移除了冗余的重复导入语句

内容的提问来源于stack exchange,提问作者Jatin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:57:02