ZetaHarmonics Python GUI

👤 Sharing: AI
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import random
import time
import threading
import os

# --- Utility Functions ---

def generate_random_color():
    return '#%02x%02x%02x' % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

def log_message(text):
    current_time = time.strftime('%Y-%m-%d %H:%M:%S')
    log_text.insert(tk.END, f'[{current_time}] {text}\n')
    log_text.see(tk.END)

# --- Core Application Logic ---

class ZetaHarmonicsApp:
    def __init__(self, root):
        self.root = root
        self.root.title("ZetaHarmonics: Versatile Toolkit")
        self.root.geometry("800x600")

        self.notebook = ttk.Notebook(root)
        self.notebook.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)

        self.create_text_editor_tab()
        self.create_random_data_tab()
        self.create_network_tools_tab()
        self.create_about_tab()

        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)

    def create_text_editor_tab(self):
        text_editor_tab = ttk.Frame(self.notebook)
        self.notebook.add(text_editor_tab, text="Text Editor")

        # Text Editor
        self.text_area = scrolledtext.ScrolledText(text_editor_tab, wrap=tk.WORD, font=("Arial", 12))
        self.text_area.pack(expand=True, fill=tk.BOTH, padx=5, pady=5)

        # Menu Bar (File operations)
        menubar = tk.Menu(text_editor_tab)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="New", command=self.new_file)
        filemenu.add_command(label="Open", command=self.open_file)
        filemenu.add_command(label="Save", command=self.save_file)
        filemenu.add_command(label="Save As...", command=self.save_file_as)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.root.destroy)
        menubar.add_cascade(label="File", menu=filemenu)
        self.root.config(menu=menubar)

    def create_random_data_tab(self):
        random_data_tab = ttk.Frame(self.notebook)
        self.notebook.add(random_data_tab, text="Random Data Generator")

        # Number of entries
        ttk.Label(random_data_tab, text="Number of Entries:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.W)
        self.num_entries_entry = ttk.Entry(random_data_tab)
        self.num_entries_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.E)
        self.num_entries_entry.insert(0, "10")

        # Data Type
        ttk.Label(random_data_tab, text="Data Type:").grid(row=1, column=0, padx=5, pady=5, sticky=tk.W)
        self.data_type_combo = ttk.Combobox(random_data_tab, values=["Integer", "Float", "String"])
        self.data_type_combo.grid(row=1, column=1, padx=5, pady=5, sticky=tk.E)
        self.data_type_combo.set("Integer")

        # Generate Button
        generate_button = ttk.Button(random_data_tab, text="Generate Data", command=self.generate_random_data)
        generate_button.grid(row=2, column=0, columnspan=2, padx=5, pady=10)

        # Result Text Area
        self.data_output_area = scrolledtext.ScrolledText(random_data_tab, wrap=tk.WORD, height=10)
        self.data_output_area.grid(row=3, column=0, columnspan=2, padx=5, pady=5, sticky=tk.NSEW)

    def create_network_tools_tab(self):
        network_tools_tab = ttk.Frame(self.notebook)
        self.notebook.add(network_tools_tab, text="Network Tools")

        ttk.Label(network_tools_tab, text="Ping Target:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.W)
        self.ping_target_entry = ttk.Entry(network_tools_tab)
        self.ping_target_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.E)
        self.ping_target_entry.insert(0, "google.com")

        ping_button = ttk.Button(network_tools_tab, text="Ping", command=self.run_ping)
        ping_button.grid(row=1, column=0, columnspan=2, padx=5, pady=10)

        self.ping_output_area = scrolledtext.ScrolledText(network_tools_tab, wrap=tk.WORD, height=10)
        self.ping_output_area.grid(row=2, column=0, columnspan=2, padx=5, pady=5, sticky=tk.NSEW)

    def create_about_tab(self):
        about_tab = ttk.Frame(self.notebook)
        self.notebook.add(about_tab, text="About")

        about_text = "ZetaHarmonics is a versatile toolkit designed to demonstrate various Python capabilities. It includes a text editor, random data generator, and network tools.\n\nCreated with Tkinter."
        about_label = ttk.Label(about_tab, text=about_text, wraplength=600, justify=tk.LEFT)
        about_label.pack(padx=20, pady=20)

        details_button = ttk.Button(about_tab, text="Details", command=self.show_details)
        details_button.pack(pady=10)

    # --- Text Editor Functions ---
    def new_file(self):
        self.text_area.delete("1.0", tk.END)

    def open_file(self):
        filepath = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt"), ("All Files", "*")])
        if filepath:
            try:
                with open(filepath, "r") as file:
                    content = file.read()
                    self.text_area.delete("1.0", tk.END)
                    self.text_area.insert(tk.END, content)
            except Exception as e:
                messagebox.showerror("Error", f"Could not open file: {e}")

    def save_file(self):
        if hasattr(self, 'current_filepath') and self.current_filepath:
            try:
                with open(self.current_filepath, "w") as file:
                    content = self.text_area.get("1.0", tk.END)
                    file.write(content)
                messagebox.showinfo("Save", "File saved successfully!")
            except Exception as e:
                messagebox.showerror("Error", f"Could not save file: {e}")
        else:
            self.save_file_as()

    def save_file_as(self):
        filepath = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*")])
        if filepath:
            try:
                with open(filepath, "w") as file:
                    content = self.text_area.get("1.0", tk.END)
                    file.write(content)
                self.current_filepath = filepath
                messagebox.showinfo("Save", "File saved successfully!")
            except Exception as e:
                messagebox.showerror("Error", f"Could not save file: {e}")

    # --- Random Data Functions ---
    def generate_random_data(self):
        try:
            num_entries = int(self.num_entries_entry.get())
            data_type = self.data_type_combo.get()

            data = []
            for _ in range(num_entries):
                if data_type == "Integer":
                    data.append(random.randint(1, 100))
                elif data_type == "Float":
                    data.append(random.uniform(0, 1))
                elif data_type == "String":
                    data.append(''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(5)))

            self.data_output_area.delete("1.0", tk.END)
            self.data_output_area.insert(tk.END, '\n'.join(map(str, data)))
        except ValueError:
            messagebox.showerror("Error", "Invalid number of entries.")

    # --- Network Tools Functions ---
    def run_ping(self):
        target = self.ping_target_entry.get()
        self.ping_output_area.delete("1.0", tk.END)
        self.ping_output_area.insert(tk.END, f"Pinging {target}...\n")

        def ping_thread():
            try:
                import subprocess
                process = subprocess.Popen(['ping', target, '-n', '4'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                stdout, stderr = process.communicate()
                output = stdout.decode('utf-8')
                self.ping_output_area.insert(tk.END, output)
            except FileNotFoundError:
                self.ping_output_area.insert(tk.END, "Ping command not found.  Please ensure ping is available in your system's PATH.")
            except Exception as e:
                self.ping_output_area.insert(tk.END, f"An error occurred: {e}")

        threading.Thread(target=ping_thread).start()

    # --- About Details ---
    def show_details(self):
        details_window = tk.Toplevel(self.root)
        details_window.title("ZetaHarmonics Details")

        details_text = "ZetaHarmonics is built using Tkinter for the GUI.  It includes basic text editing functionalities (New, Open, Save, Save As), a random data generator allowing you to generate integers, floats, or random strings, and a simple network ping utility.\n\nThe application is designed to be cross-platform and demonstrates various Python features. Future updates may include more advanced features and tools."

        details_label = tk.Label(details_window, text=details_text, wraplength=500, justify=tk.LEFT)
        details_label.pack(padx=20, pady=20)

    def on_closing(self):
        if messagebox.askokcancel("Quit", "Do you want to quit?"):
            self.root.destroy()

# --- Main Execution ---

if __name__ == "__main__":
    root = tk.Tk()
    app = ZetaHarmonicsApp(root)
    root.mainloop()
👁️ Viewed: 6

Comments