Xenith Data Weaver Python GUI

👤 Sharing: AI
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import json

class DataWeaverApp:
    def __init__(self, master):
        self.master = master
        master.title("Xenith Data Weaver")
        master.geometry("800x600")

        self.notebook = ttk.Notebook(master)
        self.notebook.pack(fill='both', expand=True)

        self.create_data_tab()
        self.create_analysis_tab()
        self.create_settings_tab()

        self.create_menu()

    def create_menu(self):
        menubar = tk.Menu(self.master)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open", command=self.load_data)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.master.quit)
        menubar.add_cascade(label="File", menu=filemenu)

        helpmenu = tk.Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", command=self.show_about)
        menubar.add_cascade(label="Help", menu=helpmenu)

        self.master.config(menu=menubar)


    def create_data_tab(self):
        self.data_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.data_tab, text='Data Explorer')

        self.data_text = tk.Text(self.data_tab, wrap=tk.WORD)
        self.data_text.pack(fill='both', expand=True)

        self.load_button = tk.Button(self.data_tab, text="Load Data (CSV/JSON)", command=self.load_data)
        self.load_button.pack()

    def create_analysis_tab(self):
        self.analysis_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.analysis_tab, text='Data Analysis')

        self.analysis_text = tk.Text(self.analysis_tab, wrap=tk.WORD)
        self.analysis_text.pack(fill='both', expand=True)

        self.plot_button = tk.Button(self.analysis_tab, text="Generate Plot", command=self.generate_plot)
        self.plot_button.pack()

        self.analysis_var = tk.StringVar(value="Mean")
        self.analysis_options = ttk.Combobox(self.analysis_tab, textvariable=self.analysis_var, values=["Mean", "Median", "Standard Deviation", "Correlation"])
        self.analysis_options.pack()

    def create_settings_tab(self):
        self.settings_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.settings_tab, text='Settings')

        self.theme_label = tk.Label(self.settings_tab, text="Theme:")
        self.theme_label.pack()

        self.theme_var = tk.StringVar(value="Light")
        self.theme_options = ttk.Combobox(self.settings_tab, textvariable=self.theme_var, values=["Light", "Dark"])
        self.theme_options.pack()
        self.theme_options.bind("<<ComboboxSelected>>", self.apply_theme)

    def load_data(self):
        file_path = filedialog.askopenfilename(filetypes=[("CSV Files", "*.csv"), ("JSON Files", "*.json"), ("All files", "*")])
        if file_path:
            try:
                if file_path.endswith(".csv"):
                    self.df = pd.read_csv(file_path)
                elif file_path.endswith(".json"):
                    self.df = pd.read_json(file_path)
                else:
                    self.data_text.insert(tk.END, "Unsupported file format.")
                    return

                self.data_text.delete("1.0", tk.END)
                self.data_text.insert(tk.END, self.df.to_string())
            except Exception as e:
                self.data_text.delete("1.0", tk.END)
                self.data_text.insert(tk.END, f"Error loading data: {e}")

    def generate_plot(self):
        try:
            if not hasattr(self, 'df'):
                self.analysis_text.insert(tk.END, "No data loaded. Please load data first.")
                return

            #Basic Error Handling - check for numeric Data
            numeric_columns = self.df.select_dtypes(include=['number']).columns
            if len(numeric_columns) < 2:
                 self.analysis_text.delete("1.0", tk.END)
                 self.analysis_text.insert(tk.END, "Insufficient numeric data for plotting.  At least two numeric columns required.")
                 return

            x_col = numeric_columns[0]
            y_col = numeric_columns[1]


            analysis_type = self.analysis_var.get()

            self.analysis_text.delete("1.0", tk.END)
            if analysis_type == "Mean":
                self.analysis_text.insert(tk.END, f"Mean of {y_col}: {self.df[y_col].mean()}")
            elif analysis_type == "Median":
                self.analysis_text.insert(tk.END, f"Median of {y_col}: {self.df[y_col].median()}")
            elif analysis_type == "Standard Deviation":
                self.analysis_text.insert(tk.END, f"Standard Deviation of {y_col}: {self.df[y_col].std()}")
            elif analysis_type == "Correlation":
                try:
                    correlation = self.df[x_col].corr(self.df[y_col])
                    self.analysis_text.insert(tk.END, f"Correlation between {x_col} and {y_col}: {correlation}")
                except Exception as e:
                    self.analysis_text.insert(tk.END, f"Error calculating correlation: {e}")

            # Generate Plot
            fig, ax = plt.subplots()
            ax.plot(self.df[x_col], self.df[y_col])
            ax.set_xlabel(x_col)
            ax.set_ylabel(y_col)
            ax.set_title(f'Plot of {x_col} vs {y_col}')

            canvas = FigureCanvasTkAgg(fig, master=self.analysis_tab)
            canvas.draw()
            canvas.get_tk_widget().pack()

            # Clean up previous plot if it exists
            if hasattr(self, 'previous_canvas'):
                self.previous_canvas.get_tk_widget().destroy()

            self.previous_canvas = canvas # Save the canvas for future cleanup



        except Exception as e:
            self.analysis_text.delete("1.0", tk.END)
            self.analysis_text.insert(tk.END, f"Error generating plot: {e}")


    def apply_theme(self, event=None):
        theme = self.theme_var.get()
        if theme == "Dark":
            self.master.configure(bg="#333333")
            self.data_text.configure(bg="#444444", fg="#FFFFFF")
            self.analysis_text.configure(bg="#444444", fg="#FFFFFF")
        else:
            self.master.configure(bg="#F0F0F0")
            self.data_text.configure(bg="#FFFFFF", fg="#000000")
            self.analysis_text.configure(bg="#FFFFFF", fg="#000000")

    def show_about(self):
        about_window = tk.Toplevel(self.master)
        about_window.title("About Xenith Data Weaver")
        about_label = tk.Label(about_window, text="Xenith Data Weaver is a versatile data analysis tool. \nIt allows users to load, explore, and analyze data from CSV and JSON files.\nVersion 1.0")
        about_label.pack(padx=20, pady=20)

root = tk.Tk()
app = DataWeaverApp(root)
root.mainloop()
👁️ Viewed: 9

Comments