J_VersatileAssistant Python GUI

👤 Sharing: AI
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import datetime

class VersatileAssistant:
    def __init__(self, master):
        self.master = master
        master.title("Versatile Assistant")
        master.geometry("600x400")

        # Notebook (Tab Control)
        self.notebook = ttk.Notebook(master)
        self.notebook.pack(expand=True, fill='both', padx=10, pady=10)

        # --- Tab 1: Text Editor --- 
        self.text_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.text_tab, text='Text Editor')

        self.text_area = tk.Text(self.text_tab, wrap='word', undo=True)
        self.text_area.pack(expand=True, fill='both', padx=5, pady=5)

        # Text Editor Menu
        self.text_menu_bar = tk.Menu(self.text_tab)
        file_menu = tk.Menu(self.text_menu_bar, tearoff=0)
        file_menu.add_command(label="New", command=self.new_file)
        file_menu.add_command(label="Open", command=self.open_file)
        file_menu.add_command(label="Save", command=self.save_file)
        file_menu.add_command(label="Save As...", command=self.save_file_as)
        file_menu.add_separator()
        file_menu.add_command(label="Exit", command=master.quit)
        self.text_menu_bar.add_cascade(label="File", menu=file_menu)
        master.config(menu=self.text_menu_bar)

        # --- Tab 2: Date & Time Converter --- 
        self.date_time_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.date_time_tab, text='Date/Time Converter')

        self.date_label = tk.Label(self.date_time_tab, text="Enter Date (YYYY-MM-DD):")
        self.date_label.pack(pady=5)
        self.date_entry = tk.Entry(self.date_time_tab)
        self.date_entry.pack(pady=5)

        self.time_label = tk.Label(self.date_time_tab, text="Enter Time (HH:MM:SS):")
        self.time_label.pack(pady=5)
        self.time_entry = tk.Entry(self.date_time_tab)
        self.time_entry.pack(pady=5)

        self.convert_button = tk.Button(self.date_time_tab, text="Convert to Timestamp", command=self.convert_to_timestamp)
        self.convert_button.pack(pady=10)

        self.timestamp_result = tk.StringVar()
        self.timestamp_label = tk.Label(self.date_time_tab, textvariable=self.timestamp_result)
        self.timestamp_label.pack(pady=5)

        # --- Tab 3: Simple Calculator --- 
        self.calculator_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.calculator_tab, text='Simple Calculator')

        self.calc_entry = tk.Entry(self.calculator_tab)
        self.calc_entry.pack(pady=5, padx=5)

        button_frame = tk.Frame(self.calculator_tab)
        button_frame.pack()

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+'
        ]

        row, col = 0, 0
        for button_text in buttons:
            button = tk.Button(button_frame, text=button_text, width=4, height=2,
                                command=lambda text=button_text: self.calculator_click(text))
            button.grid(row=row, column=col, padx=2, pady=2)
            col += 1
            if col > 3:
                col = 0
                row += 1
        
        self.clear_button = tk.Button(button_frame, text="Clear", width=16, height=2, command=self.calculator_clear)
        self.clear_button.grid(row=row+1, column=0, columnspan=4, padx=2, pady=2)

        # --- About Button --- 
        self.about_button = tk.Button(master, text="About", command=self.show_about)
        self.about_button.pack(pady=10)

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

    def open_file(self):
        file_path = filedialog.askopenfilename()
        if file_path:
            try:
                with open(file_path, "r") as file:
                    self.text_area.delete("1.0", tk.END)
                    self.text_area.insert(tk.END, file.read())
            except Exception as e:
                messagebox.showerror("Error", f"Could not open file: {e}")

    def save_file(self):
        if hasattr(self, 'current_file_path'):
            try:
                with open(self.current_file_path, "w") as file:
                    file.write(self.text_area.get("1.0", tk.END))
            except Exception as e:
                messagebox.showerror("Error", f"Could not save file: {e}")
        else:
            self.save_file_as()

    def save_file_as(self):
        file_path = filedialog.asksaveasfilename(defaultextension=".txt")
        if file_path:
            try:
                with open(file_path, "w") as file:
                    file.write(self.text_area.get("1.0", tk.END))
                self.current_file_path = file_path  # Store the file path
            except Exception as e:
                messagebox.showerror("Error", f"Could not save file: {e}")

    # --- Date & Time Converter Functions --- 
    def convert_to_timestamp(self):
        date_str = self.date_entry.get()
        time_str = self.time_entry.get()

        try:
            dt_str = f"{date_str} {time_str}"
            dt_object = datetime.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
            timestamp = dt_object.timestamp()
            self.timestamp_result.set(f"Timestamp: {timestamp}")
        except ValueError:
            self.timestamp_result.set("Invalid date or time format")
        except Exception as e:
            self.timestamp_result.set(f"Error: {e}")

    # --- Calculator Functions --- 
    def calculator_click(self, char):
        current_text = self.calc_entry.get()
        self.calc_entry.delete(0, tk.END)
        self.calc_entry.insert(0, current_text + char)

        if char == '=':
            try:
                result = eval(current_text)
                self.calc_entry.delete(0, tk.END)
                self.calc_entry.insert(0, str(result))
            except Exception:
                self.calc_entry.delete(0, tk.END)
                self.calc_entry.insert(0, "Error")

    def calculator_clear(self):
        self.calc_entry.delete(0, tk.END)

    # --- About Function --- 
    def show_about(self):
        about_message = """Versatile Assistant: Your all-in-one utility tool.\n\nFeatures:\n- Text Editor: Create, open, save, and edit text files.\n- Date/Time Converter: Convert dates and times to timestamps.\n- Simple Calculator: Perform basic arithmetic operations.\n\nCreated to showcase Python GUI capabilities and provide practical functionality."""
        messagebox.showinfo("About Versatile Assistant", about_message)


root = tk.Tk()
my_gui = VersatileAssistant(root)
root.mainloop()
👁️ Viewed: 8

Comments