Zenith Data Alchemist Python GUI

👤 Sharing: AI
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import io
import base64
from PIL import Image, ImageTk
import numpy as np

class DataAlchemist:
    def __init__(self, master):
        self.master = master
        master.title("Zenith Data Alchemist")

        # Notebook (Tabs)
        self.notebook = ttk.Notebook(master)
        self.notebook.pack(expand=True, fill="both", padx=10, pady=10)

        # CSV Viewer Tab
        self.csv_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.csv_tab, text="CSV Viewer")
        self.create_csv_viewer()

        # Image Converter Tab
        self.image_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.image_tab, text="Image Converter")
        self.create_image_converter()

        # Function Explorer Tab
        self.function_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.function_tab, text="Function Explorer")
        self.create_function_explorer()

        # Details Button (Global)
        self.details_button = tk.Button(master, text="Details", command=self.show_details, bg="#4CAF50", fg="white", font=("Arial", 10))
        self.details_button.pack(pady=5)

        self.details_content = {
            "CSV Viewer": "Load, view, and visualize CSV data.  Includes filtering and basic plotting. Supports large CSV files.",
            "Image Converter": "Convert images between various formats (PNG, JPG, GIF).  Offers basic resizing and quality adjustments.",
            "Function Explorer": "Explore Python's built-in functions with interactive examples and documentation lookup."
        }

        self.current_tab = "CSV Viewer"  # Default tab
        self.notebook.bind("<ButtonRelease-1>", self.tab_changed)


    def tab_changed(self, event):  # Added this method
        self.current_tab = self.notebook.tab(self.notebook.select(), "text")

    def show_details(self):
        messagebox.showinfo("Details", self.details_content[self.current_tab])


    def create_csv_viewer(self):
        # CSV Loading and Display
        self.csv_frame = tk.Frame(self.csv_tab)
        self.csv_frame.pack(expand=True, fill="both", padx=5, pady=5)

        self.load_csv_button = tk.Button(self.csv_frame, text="Load CSV", command=self.load_csv, bg="#2196F3", fg="white", font=("Arial", 10))
        self.load_csv_button.pack(pady=5)

        self.csv_text = scrolledtext.ScrolledText(self.csv_frame, wrap=tk.WORD)
        self.csv_text.pack(expand=True, fill="both")

        # Filtering
        self.filter_label = tk.Label(self.csv_frame, text="Filter Column:")
        self.filter_label.pack()
        self.filter_column_entry = tk.Entry(self.csv_frame)
        self.filter_column_entry.pack()

        self.filter_value_label = tk.Label(self.csv_frame, text="Filter Value:")
        self.filter_value_label.pack()
        self.filter_value_entry = tk.Entry(self.csv_frame)
        self.filter_value_entry.pack()

        self.filter_button = tk.Button(self.csv_frame, text="Apply Filter", command=self.apply_filter, bg="#FF9800", fg="white", font=("Arial", 10))
        self.filter_button.pack(pady=5)

        # Plotting
        self.plot_button = tk.Button(self.csv_frame, text="Plot Data", command=self.plot_data, bg="#9C27B0", fg="white", font=("Arial", 10))
        self.plot_button.pack(pady=5)

        self.df = None # Store the dataframe

    def create_image_converter(self):
        # Image Loading, Conversion, and Display
        self.image_frame = tk.Frame(self.image_tab)
        self.image_frame.pack(expand=True, fill="both", padx=5, pady=5)

        self.load_image_button = tk.Button(self.image_frame, text="Load Image", command=self.load_image, bg="#2196F3", fg="white", font=("Arial", 10))
        self.load_image_button.pack(pady=5)

        self.image_label = tk.Label(self.image_frame) # For displaying the image
        self.image_label.pack()

        # Conversion Options
        self.format_label = tk.Label(self.image_frame, text="Convert to Format:")
        self.format_label.pack()
        self.format_combo = ttk.Combobox(self.image_frame, values=["PNG", "JPEG", "GIF", "BMP"])
        self.format_combo.pack()
        self.format_combo.set("PNG")

        self.convert_button = tk.Button(self.image_frame, text="Convert Image", command=self.convert_image, bg="#4CAF50", fg="white", font=("Arial", 10))
        self.convert_button.pack(pady=5)

        self.img_data = None  # Store image data

    def create_function_explorer(self):
        # Python Function Exploration
        self.function_frame = tk.Frame(self.function_tab)
        self.function_frame.pack(expand=True, fill="both", padx=5, pady=5)

        self.function_label = tk.Label(self.function_frame, text="Enter Function Name:")
        self.function_label.pack()
        self.function_entry = tk.Entry(self.function_frame)
        self.function_entry.pack()

        self.explore_button = tk.Button(self.function_frame, text="Explore Function", command=self.explore_function, bg="#E91E63", fg="white", font=("Arial", 10))
        self.explore_button.pack(pady=5)

        self.function_text = scrolledtext.ScrolledText(self.function_frame, wrap=tk.WORD)
        self.function_text.pack(expand=True, fill="both")


    def load_csv(self):
        from tkinter import filedialog
        filename = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
        if filename:
            try:
                self.df = pd.read_csv(filename)
                self.csv_text.delete("1.0", tk.END)
                self.csv_text.insert(tk.END, self.df.to_string())
            except Exception as e:
                messagebox.showerror("Error", f"Error loading CSV: {e}")

    def apply_filter(self):
        if self.df is None:
            messagebox.showerror("Error", "Load CSV first.")
            return

        column = self.filter_column_entry.get()
        value = self.filter_value_entry.get()
        try:
            filtered_df = self.df[self.df[column] == value]
            self.csv_text.delete("1.0", tk.END)
            self.csv_text.insert(tk.END, filtered_df.to_string())
        except KeyError:
            messagebox.showerror("Error", "Invalid column name.")
        except Exception as e:
            messagebox.showerror("Error", f"Error filtering: {e}")

    def plot_data(self):
        if self.df is None:
            messagebox.showerror("Error", "Load CSV first.")
            return
        try:
            # Basic plot - you can customize this further
            fig = plt.figure(figsize=(6, 4))
            plt.plot(self.df.iloc[:, 0], self.df.iloc[:, 1]) # Assumes first two columns are x and y
            plt.xlabel(self.df.columns[0])
            plt.ylabel(self.df.columns[1])
            plt.title("Data Plot")

            # Embed the plot in the Tkinter window
            canvas = FigureCanvasTkAgg(fig, master=self.csv_frame)
            canvas.draw()
            canvas.get_tk_widget().pack()

        except Exception as e:
            messagebox.showerror("Error", f"Error plotting: {e}")

    def load_image(self):
        from tkinter import filedialog
        filename = filedialog.askopenfilename(filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.gif;*.bmp")])
        if filename:
            try:
                self.img_data = Image.open(filename)
                self.img_data.thumbnail((300, 300))
                self.img = ImageTk.PhotoImage(self.img_data)
                self.image_label.config(image=self.img)
                self.image_label.image = self.img  # Keep a reference!
            except Exception as e:
                messagebox.showerror("Error", f"Error loading image: {e}")

    def convert_image(self):
        if self.img_data is None:
            messagebox.showerror("Error", "Load image first.")
            return

        format = self.format_combo.get().lower()
        try:
            # In-memory conversion
            buffer = io.BytesIO()
            self.img_data.save(buffer, format=format)
            img_str = base64.b64encode(buffer.getvalue()).decode()

            # Display (using a dummy image label to avoid saving to disk for demonstration)
            dummy_img = tk.PhotoImage(data=img_str)
            self.image_label.config(image=dummy_img)
            self.image_label.image = dummy_img

            messagebox.showinfo("Success", f"Image converted to {format.upper()} and displayed.")

        except Exception as e:
            messagebox.showerror("Error", f"Error converting image: {e}")

    def explore_function(self):
        function_name = self.function_entry.get()
        try:
            # Attempt to get the function
            function = eval(function_name)

            # Get the docstring
            docstring = function.__doc__
            if docstring is None:
                docstring = "No documentation available."

            self.function_text.delete("1.0", tk.END)
            self.function_text.insert(tk.END, docstring)

        except NameError:
            messagebox.showerror("Error", "Function not found.")
        except Exception as e:
            messagebox.showerror("Error", f"Error: {e}")



root = tk.Tk()
app = DataAlchemist(root)
root.mainloop()
👁️ Viewed: 8

Comments