如何在Python Spyder中用Tkinter实现调用Excel关联DataFrame的均值查询弹窗
Got it, let's build this Tkinter popup step by step to meet your exact needs. Here's a complete, working implementation that loads your Excel data, creates the input/button UI, and handles the mean calculation logic:
Complete Implementation
import tkinter as tk from tkinter import messagebox import pandas as pd # ---------------------- # Step 1: Load Excel Data # ---------------------- # Map your codes to their respective Excel files # Replace these file paths with your actual Excel locations code_to_df = { "cgk": pd.read_excel("cgk_data.xlsx"), "ams": pd.read_excel("ams_data.xlsx"), # Add your other 3-4 codes and Excel paths here } # ---------------------- # Step 2: Mean Calculation Logic # ---------------------- def calculate_mean(): # Get input from the entry box and clean it up input_codes = entry.get().strip().lower() if not input_codes: messagebox.showwarning("Input Error", "Please enter at least one code!") return # Split input into individual codes (handles spaces between entries) codes = input_codes.split() result_text = "" for code in codes: if code in code_to_df: df = code_to_df[code] # Calculate mean for all numeric columns (adjust this for specific columns) mean_values = df.mean(numeric_only=True) # Format results for readability result_text += f"=== Mean values for {code.upper()} ===\n" result_text += mean_values.to_string() + "\n\n" else: result_text += f"⚠️ Code '{code}' not found. Skipping...\n\n" # Update the result display box result_box.delete(1.0, tk.END) result_box.insert(tk.END, result_text) # ---------------------- # Step 3: Build the Tkinter UI # ---------------------- # Create main window root = tk.Tk() root.title("DataFrame Mean Calculator") root.geometry("600x400") # Set initial window size # Input section input_label = tk.Label(root, text="Enter code(s) (e.g., cgk ams):") input_label.pack(pady=10) entry = tk.Entry(root, width=50) entry.pack(pady=5) # Mean calculation button mean_btn = tk.Button(root, text="Mean value", command=calculate_mean, padx=10, pady=5) mean_btn.pack(pady=10) # Result display section result_label = tk.Label(root, text="Calculation Results:") result_label.pack(pady=5) result_box = tk.Text(root, height=15, width=70) result_box.pack(pady=5, padx=10) # Start the Tkinter loop root.mainloop()
Key Customization Points
- Excel File Paths: Replace the file paths in the
code_to_dfdictionary with your actual Excel locations. Add all 5-6 of your code-DataFrame mappings here. - Target Columns for Mean: The current code calculates means for all numeric columns. If you need to focus on specific columns only, modify the mean line to:
Just list the columns you want to include inside the brackets.mean_values = df[["your_column1", "your_column2"]].mean() - UI Tweaks: Adjust the window size (
geometry), button colors, or result display (e.g., use aLabelinstead ofTextfor simpler output) based on your preferences. - Error Handling: The code already handles empty inputs and unknown codes, but you can expand this (e.g., add try/except blocks to catch Excel load errors) if needed.
How It Works
- Data Loading: When the script starts, it loads all your Excel files into DataFrames and stores them in a dictionary keyed by their codes.
- User Input: Type one or more codes (separated by spaces) into the entry box.
- Calculation Trigger: Clicking the "Mean value" button runs the
calculate_meanfunction, which validates input, fetches the matching DataFrame(s), computes numeric column means, and formats the results. - Result Display: Results (or error messages) show up in the text box below the button for easy reading.
内容的提问来源于stack exchange,提问作者yosam
相关产品推荐
相关产品推荐

