Untitled
unknown
plain_text
12 days ago
9.8 kB
3
Indexable
Never
import tkinter as tk from tkinter import PhotoImage, filedialog, messagebox from PIL import Image, ImageTk import json import os class Stack: def __init__(self): self.posts = [] def is_empty(self): return len(self.posts) == 0 def add_post(self, post): self.posts.append(post) def get_all_posts(self): return self.posts[::-1] # Return in LIFO order class GUI: def __init__(self, root, logged_in_email): self.root = root self.logged_in_email = logged_in_email self.root.title("Home Page") self.root.geometry("800x600") self.root.configure(bg="#2b2b2b") welcome_label = tk.Label(root, text=f"Welcome, {self.logged_in_email}!", font=('Arial', 20), bg='#2b2b2b', fg='white') welcome_label.pack(pady=10) self.post_stack = Stack() # Initialize stack for posts self.load_posts() # Load posts into the stack from the JSON file self.add_post_section() self.canvas = tk.Canvas(self.root, bg="#2b2b2b", highlightthickness=0) self.canvas.pack(side="left", fill="both", expand=True) self.scrollbar = tk.Scrollbar(self.root, orient="vertical", command=self.canvas.yview) self.scrollbar.pack(side="right", fill="y") self.canvas.configure(yscrollcommand=self.scrollbar.set) self.wrapper_frame = tk.Frame(self.canvas, bg="#2b2b2b") self.canvas_window = self.canvas.create_window((0, 0), window=self.wrapper_frame, anchor="n") self.wrapper_frame.bind("<Configure>", self.update_scroll_region) self.root.bind("<Configure>", self.center_content) self.display_posts() # Load and display posts when initializing def update_scroll_region(self, event=None): self.canvas.configure(scrollregion=self.canvas.bbox("all")) def center_content(self, event=None): canvas_width = self.canvas.winfo_width() content_width = self.wrapper_frame.winfo_width() if content_width < canvas_width: self.canvas.itemconfig(self.canvas_window, width=canvas_width) else: self.canvas.itemconfig(self.canvas_window, width=content_width) def add_post_section(self): add_post_frame = tk.Frame(self.root, bg="#2b2b2b") add_post_frame.pack(pady=20) add_post_label = tk.Label(add_post_frame, text="What's on your mind?", font=('Arial', 16), bg='#2b2b2b', fg='white') add_post_label.pack(pady=5) self.new_post_entry = tk.Entry(add_post_frame, width=50, bg="white", fg="black") self.new_post_entry.pack(pady=5) self.image_path = None select_image_button = tk.Button(add_post_frame, text="Select Image", command=self.select_image, bg="blue", fg="white", padx=10, pady=5) select_image_button.pack(pady=5) add_post_button = tk.Button(add_post_frame, text="Add Post", command=self.add_new_post, bg="red", fg="white", padx=10, pady=5) add_post_button.pack(pady=10) def select_image(self): self.image_path = filedialog.askopenfilename(title="Select an image", filetypes=[("Image Files", "*.png;*.jpg;*.jpeg")]) if self.image_path: messagebox.showinfo("Image Selected", f"Image selected: {os.path.basename(self.image_path)}") def display_posts(self): self.clear_wrapper_frame() for post in self.post_stack.get_all_posts(): # Use the stack to display posts in LIFO order self.create_post_card(post) def create_post_card(self, post): card_frame = tk.Frame(self.wrapper_frame, bg="#404040", bd=2, relief="groove") card_frame.pack(pady=10, padx=10, fill="x") if "image" in post and post["image"]: post_image = self.load_image(post["image"], (200, 150)) if post_image: img_label = tk.Label(card_frame, image=post_image, bg="#404040") img_label.image = post_image # Keep a reference img_label.pack(anchor="center", padx=10, pady=5) post_label = tk.Label(card_frame, text=f"Post by {post['username']}: {post['caption']}", font=('Arial', 16), bg='#404040', fg='white') post_label.pack(pady=5) likes_label = tk.Label(card_frame, text=f"Likes: {post['likes']}", font=('Arial', 12), bg='#404040', fg='white') likes_label.pack(pady=5) like_button = tk.Button(card_frame, text="Like", command=self.create_toggle_like(post, likes_label), bg="red", fg="white", padx=10, pady=5) like_button.pack(pady=5) comment_label = tk.Label(card_frame, text="Add a comment:", bg='#404040', fg='white') comment_label.pack(pady=5) comment_entry = tk.Entry(card_frame, width=40, bg="white", fg="black") comment_entry.pack(pady=5) comment_button = tk.Button(card_frame, text="Comment", command=lambda p=post, e=comment_entry, cf=card_frame: self.comment(p, e, cf), bg="red", fg="white", padx=10, pady=5) comment_button.pack(pady=10) comments_frame = tk.Frame(card_frame, bg='#404040') comments_frame.pack(pady=5) for comment in post.get('comments', []): comment_label = tk.Label(comments_frame, text=f"Comment: {comment}", font=('Arial', 10), bg='#e0e0e0', fg='black') comment_label.pack(padx=20, pady=2) card_frame.comments_frame = comments_frame def load_posts(self): try: with open('posts.json', 'r') as file: all_posts = json.load(file) for email, posts in all_posts.items(): for post in posts: post['username'] = email # Assign email as username for display self.post_stack.add_post(post) # Add posts to the stack except FileNotFoundError: print("posts.json file not found.") except json.JSONDecodeError as e: print(f"Error decoding JSON from posts.json: {e}") def create_toggle_like(self, post, likes_label): def toggle_like(): post['likes'] += 1 # Increment likes for simplicity likes_label.config(text=f"Likes: {post['likes']}") self.save_posts() # Save the updated post data return toggle_like def clear_wrapper_frame(self): for widget in self.wrapper_frame.winfo_children(): widget.destroy() def add_new_post(self): new_post_text = self.new_post_entry.get() if new_post_text or self.image_path: new_post = { "caption": new_post_text, "likes": 0, "comments": [], "image": self.image_path, "username": self.logged_in_email # Use the logged-in user's email } self.post_stack.add_post(new_post) # Add the new post to the stack self.save_post(new_post) # Save the new post to JSON self.new_post_entry.delete(0, tk.END) self.image_path = None self.display_posts() # Refresh the post display else: messagebox.showerror("Error", "Please provide either an image or a caption.") def load_image(self, image_path, size): try: image = Image.open(image_path) image = image.resize(size, Image.LANCZOS) return ImageTk.PhotoImage(image) except Exception as e: print(f"Error loading image: {e}") return None def save_posts(self): all_posts = {} for post in self.post_stack.get_all_posts(): email = post['username'] if email in all_posts: all_posts[email].append(post) else: all_posts[email] = [post] with open('posts.json', 'w') as file: json.dump(all_posts, file, indent=4) def save_post(self, new_post): all_posts = {} try: with open('posts.json', 'r') as file: all_posts = json.load(file) except FileNotFoundError: pass except json.JSONDecodeError as e: print(f"Error decoding JSON from posts.json: {e}") email = new_post['username'] if email in all_posts: all_posts[email].append(new_post) else: all_posts[email] = [new_post] with open('posts.json', 'w') as file: json.dump(all_posts, file, indent=4) def comment(self, post, comment_entry, card_frame): comment_text = comment_entry.get() if comment_text: post['comments'].append(comment_text) self.save_posts() # Save the updated comments comment_entry.delete(0, tk.END) new_comment_label = tk.Label(card_frame.comments_frame, text=f"Comment: {comment_text}", font=('Arial', 10), bg='#e0e0e0', fg='black') new_comment_label.pack(padx=20, pady=2) else: messagebox.showerror("Error", "Comment cannot be empty.") if __name__ == "__main__": root = tk.Tk() app = GUI(root, "user@example.com") # Pass the logged-in email root.mainloop()
Leave a Comment