Untitled
unknown
plain_text
a year ago
13 kB
5
Indexable
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 remove_post(self):
return None if self.is_empty() else self.posts.pop()
def get_all_posts(self):
return self.posts
class GUI:
def __init__(self, root, email):
self.root = root
self.email = email
self.root.title("Home Page")
self.root.geometry("800x600")
self.root.configure(bg="#2b2b2b")
self.profile_image = PhotoImage(file="C:/Users/ACER/Desktop/samsung innovation campus/avatar.png")
welcome_label = tk.Label(root, text="Welcome back!", font=('Arial', 20), image=self.profile_image, compound='left',
bg='#2b2b2b', fg='white')
welcome_label.pack(pady=10)
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", width=600)
self.wrapper_frame.bind("<Configure>", self.update_scroll_region)
self.root.bind("<Configure>", self.center_content)
self.post_stack = Stack()
self.load_posts('posts.json')
self.display_posts()
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()
# Load user's posts
user_posts = self.post_stack.get_all_posts()
# Load friends' posts
friends_posts = self.load_friends_posts()
# Combine user posts and friends' posts
all_posts = user_posts + friends_posts
for post in reversed(all_posts):
card_frame = tk.Frame(self.wrapper_frame, bg="#404040", bd=2, relief="groove")
card_frame.pack(pady=10, padx=10, fill="x")
# Display image if present
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
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)
if 'liked' not in post:
post['liked'] = False
like_button = tk.Button(card_frame, text="Like" if not post['liked'] else "Unlike",
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['content']}", font=('Arial', 10),
bg='#e0e0e0', fg='black')
comment_label.pack(padx=20, pady=2)
card_frame.comments_frame = comments_frame
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")
# Display image if present
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
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)
if 'liked' not in post:
post['liked'] = False
like_button = tk.Button(card_frame, text="Like" if not post['liked'] else "Unlike",
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['content']}", font=('Arial', 10),
bg='#e0e0e0', fg='black')
comment_label.pack(padx=20, pady=2)
card_frame.comments_frame = comments_frame
def load_friends_posts(self):
try:
with open('users.json', 'r') as user_file:
users_data = json.load(user_file)
friends = users_data.get(self.email, {}).get("friends", [])
friends_posts = []
for friend_email in friends:
with open('posts.json', 'r') as post_file:
friend_posts_data = json.load(post_file)
if friend_email in friend_posts_data:
friends_posts.extend(friend_posts_data[friend_email])
return friends_posts
except FileNotFoundError:
print("users.json file not found.")
return []
except json.JSONDecodeError as e:
print(f"Error decoding JSON from users.json: {e}")
return []
def create_toggle_like(self, post, likes_label):
def toggle_like():
if post['liked']:
post['likes'] -= 1
post['liked'] = False
likes_label.config(text=f"Likes: {post['likes']}")
else:
post['likes'] += 1
post['liked'] = True
likes_label.config(text=f"Likes: {post['likes']}")
self.save_posts()
return toggle_like
def clear_wrapper_frame(self):
for widget in self.wrapper_frame.winfo_children():
widget.destroy()
def save_posts(self):
# Load existing data from the JSON file
try:
with open('posts.json', 'r') as file:
all_data = json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
all_data = {} # Initialize as empty if file not found or JSON error
# Update the data with the current user's posts
all_data[self.email] = self.post_stack.get_all_posts()
# Save the updated data back to the JSON file
with open('posts.json', 'w') as file:
json.dump(all_data, file, indent=4)
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": [],
"username": "User", # You may want to replace "User" with actual username
"image": self.image_path
}
self.post_stack.add_post(new_post)
self.new_post_entry.delete(0, tk.END)
self.image_path = None
self.save_posts() # Save posts after adding a new one
self.display_posts()
else:
messagebox.showerror("Error", "Please provide either an image and 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 = self.post_stack.get_all_posts()
with open('posts.json', 'w') as file:
json.dump({self.email: all_posts}, file, indent=4)
def load_posts(self, filename):
try:
with open(filename, 'r') as file:
data = json.load(file)
if isinstance(data, dict):
userposts = data.get(self.email, [])
for post in userposts:
self.post_stack.add_post(post)
else:
print("The data loaded from posts.json is not in the expected format.")
except FileNotFoundError:
print("posts.json file not found. Initializing with empty data.")
self.save_posts() # Create an empty posts.json file
except json.JSONDecodeError:
print("Error decoding JSON from posts.json. Initializing with empty data.")
self.save_posts() # Create an empty posts.json file
if __name__ == "__main__":
root = tk.Tk()
email = "user@example.com" # Replace with the actual email of the logged-in user
gui = GUI(root, email)
root.mainloop()
#Editor is loading...
Leave a Comment