import tkinter as tk from tkinter import scrolledtext, messagebox import json import os from datetime import datetime class ChatApplication: def __init__(self, root): self.root = root self.root.title("Chat Interface") self.root.geometry("600x500") self.root.configure(bg="#f0f0f0") self.message_history = [] self.history_file = "chat_history.json" self.load_chat_history() self.create_widgets() def create_widgets(self): # Main frame main_frame = tk.Frame(self.root, bg="#f0f0f0") main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) # Chat display area self.chat_display = scrolledtext.ScrolledText( main_frame, wrap=tk.WORD, width=60, height=20, font=("Arial", 10), state=tk.DISABLED ) self.chat_display.pack(fill=tk.BOTH, expand=True, pady=(0, 10)) # Input frame input_frame = tk.Frame(main_frame, bg="#f0f0f0") input_frame.pack(fill=tk.X) # User input field self.user_input = tk.Entry( input_frame, font=("Arial", 12), relief=tk.FLAT, bg="white" ) self.user_input.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5)) self.user_input.bind("", self.send_message) # Send button send_button = tk.Button( input_frame, text="Send", command=self.send_message, bg="#4CAF50", fg="white", font=("Arial", 10, "bold"), relief=tk.FLAT, padx=20 ) send_button.pack(side=tk.RIGHT) # Load existing messages self.display_messages() # Focus on input field self.user_input.focus_set() def send_message(self, event=None): message = self.user_input.get().strip() if not message: return timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") message_data = { "timestamp": timestamp, "message": message, "sender": "user" } self.message_history.append(message_data) self.display_message(message_data) self.user_input.delete(0, tk.END) # Simulate bot response (in real app, this would be your AI/chat logic) self.simulate_bot_response(message) self.save_chat_history() def simulate_bot_response(self, user_message): # Simple response simulation - replace with actual AI/chat logic responses = { "hello": "Hello! How can I help you today?", "hi": "Hi there! What can I do for you?", "help": "I'm here to help! What do you need assistance with?", "bye": "Goodbye! Have a great day!" } response = responses.get(user_message.lower(), f"I received your message: '{user_message}'. How can I assist you further?") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") response_data = { "timestamp": timestamp, "message": response, "sender": "bot" } self.message_history.append(response_data) self.display_message(response_data) self.save_chat_history() def display_message(self, message_data): self.chat_display.config(state=tk.NORMAL) # Configure tags for different senders self.chat_display.tag_configure("user", foreground="blue", justify="right") self.chat_display.tag_configure("bot", foreground="green", justify="left") self.chat_display.tag_configure("timestamp", foreground="gray", font=("Arial", 8)) # Insert message with appropriate formatting if message_data["sender"] == "user": self.chat_display.insert(tk.END, f"{message_data['timestamp']}\n", "timestamp") self.chat_display.insert(tk.END, f"You: {message_data['message']}\n\n", "user") else: self.chat_display.insert(tk.END, f"{message_data['timestamp']}\n", "timestamp") self.chat_display.insert(tk.END, f"Bot: {message_data['message']}\n\n", "bot") self.chat_display.config(state=tk.DISABLED) self.chat_display.see(tk.END) def display_messages(self): self.chat_display.config(state=tk.NORMAL) self.chat_display.delete(1.0, tk.END) for message in self.message_history: if message["sender"] == "user": self.chat_display.insert(tk.END, f"{message['timestamp']}\n", "timestamp") self.chat_display.insert(tk.END, f"You: {message['message']}\n\n", "user") else: self.chat_display.insert(tk.END, f"{message['timestamp']}\n", "timestamp") self.chat_display.insert(tk.END, f"Bot: {message['message']}\n\n", "bot") self.chat_display.config(state=tk.DISABLED) self.chat_display.see(tk.END) def load_chat_history(self): try: if os.path.exists(self.history_file): with open(self.history_file, 'r') as f: self.message_history = json.load(f) except (FileNotFoundError, json.JSONDecodeError): self.message_history = [] def save_chat_history(self): try: with open(self.history_file, 'w') as f: json.dump(self.message_history, f, indent=2) except Exception as e: messagebox.showerror("Error", f"Failed to save chat history: {str(e)}") def main(): root = tk.Tk() app = ChatApplication(root) root.mainloop() if __name__ == "__main__": main()