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

如何基于Tkinter实现单按钮加载并按列标题自动分配多份CSV文件至对应变量

Alright, let's fix this up for you! The goal is to replace those three separate load buttons with one that lets users select multiple CSV files, automatically sorts them into the correct variables based on their column headers, and prevents accidental overwrites. Here's a complete, refactored solution:

Key Changes Made:

  • Replaced three load buttons with a single button that supports multi-file selection
  • Added logic to identify file types by matching their column headers to pre-defined templates
  • Added overwrite confirmation prompts to avoid losing already loaded data
  • Fixed spelling errors (e.g., inventroy → inventory)
  • Added validation checks in cleaning functions to ensure files are loaded before processing

Complete Refactored Code:

import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
import csv

# Initialize main window
window1 = tk.Tk()
window1.title("CSV Processor")
window1.geometry("500x200")

# --------------------------
# Define your column templates here (match your actual CSV headers!)
# --------------------------
# Set of unique columns that identify each file type
INSPECTION_KEY_COLUMNS = {"InspectionID", "InspectionDate", "Location"}
INVENTORY_KEY_COLUMNS = {"ItemID", "ItemName", "StockQuantity"}
# Add a third template if needed, e.g.:
# MAINTENANCE_KEY_COLUMNS = {"WorkOrderID", "Technician", "Status"}

# Global variables to hold loaded data (None = not loaded)
inspectionFile = None
inventoryFile = None
# maintenanceFile = None

def loadMultipleFiles():
    global inspectionFile, inventoryFile
    # Let user select multiple CSV files
    file_paths = filedialog.askopenfilenames(
        title="Select CSV Files",
        filetypes=[("CSV Files", "*.csv")]
    )
    
    if not file_paths:
        return  # User cancelled selection
    
    for path in file_paths:
        # Read just the column headers to identify file type (fast, no need to load full file yet)
        with open(path, 'r', encoding='utf-8') as f:
            csv_reader = csv.reader(f)
            file_columns = set(next(csv_reader))
        
        # Match to inspection file
        if file_columns.issuperset(INSPECTION_KEY_COLUMNS):
            if inspectionFile is not None:
                # Ask before overwriting existing data
                if not messagebox.askyesno("Confirm Overwrite", "Inspection file is already loaded. Replace it?"):
                    continue
            inspectionFile = pd.read_csv(path)
            filename = path.split('/')[-1]
            messagebox.showinfo("Success", f"Loaded Inspection file: {filename}")
        
        # Match to inventory file
        elif file_columns.issuperset(INVENTORY_KEY_COLUMNS):
            if inventoryFile is not None:
                if not messagebox.askyesno("Confirm Overwrite", "Inventory file is already loaded. Replace it?"):
                    continue
            inventoryFile = pd.read_csv(path)
            filename = path.split('/')[-1]
            messagebox.showinfo("Success", f"Loaded Inventory file: {filename}")
        
        # Match to third file type (uncomment if needed)
        # elif file_columns.issuperset(MAINTENANCE_KEY_COLUMNS):
        #     if maintenanceFile is not None:
        #         if not messagebox.askyesno("Confirm Overwrite", "Maintenance file is already loaded. Replace it?"):
        #             continue
        #     maintenanceFile = pd.read_csv(path)
        #     filename = path.split('/')[-1]
        #     messagebox.showinfo("Success", f"Loaded Maintenance file: {filename}")
        
        # No match found
        else:
            filename = path.split('/')[-1]
            messagebox.showwarning("Unrecognized File", f"Could not identify {filename} - check column headers and try again.")

def inspectionClean():
    global inspectionFile
    if inspectionFile is None:
        messagebox.showwarning("Warning", "Please load an Inspection file first!")
        return
    # Remove duplicates (simpler syntax than your original)
    inspectionFile = inspectionFile.drop_duplicates()
    messagebox.showinfo("Complete", "Inspection data cleaned successfully!")

def inventoryClean():
    global inventoryFile
    if inventoryFile is None:
        messagebox.showwarning("Warning", "Please load an Inventory file first!")
        return
    inventoryFile = inventoryFile.drop_duplicates()
    messagebox.showinfo("Complete", "Inventory data cleaned successfully!")

# --------------------------
# UI Layout
# --------------------------
# Single load button
load_btn = tk.Button(window1, text="Load CSV Files (Multi-select)", command=loadMultipleFiles, padx=10, pady=5)
load_btn.grid(row=0, column=0, columnspan=2, pady=20)

# Cleaning buttons
clean_ins_btn = tk.Button(window1, text="Clean Inspection Data", command=inspectionClean, padx=10)
clean_ins_btn.grid(row=1, column=0, padx=20)

clean_inv_btn = tk.Button(window1, text="Clean Inventory Data", command=inventoryClean, padx=10)
clean_inv_btn.grid(row=1, column=1)

window1.mainloop()

Important Notes:

  1. Update Column Templates: Make sure to replace INSPECTION_KEY_COLUMNS and INVENTORY_KEY_COLUMNS with the actual column names from your CSVs. Use a small set of unique columns that only exist in each file type for reliable matching.
  2. Third File Type: If you have a third CSV type, uncomment the maintenance section and add its key columns.
  3. Overwrite Protection: The code will prompt users before replacing already loaded files, preventing accidental data loss.
  4. Validation: Cleaning functions now check if the file is loaded before running, avoiding errors from empty variables.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:02:30