Untitled

mail@pastecode.io avatar
unknown
plain_text
25 days ago
16 kB
2
Indexable
Never
import tkinter as tk
from tkinter import messagebox
import json
from jsonFile import handel_file_json


class Categories:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Category Selection")
        self.root.geometry("500x500")

        self.items = {
            'Home Appliances': [
                {'name': 'Washing Machine', 'price': 300, 'brand': 'LG', 'model_year': 2023},
                {'name': 'Refrigerator', 'price': 500, 'brand': 'Samsung', 'model_year': 2022},
                {'name': 'Microwave', 'price': 700, 'brand': 'Panasonic', 'model_year': 2024},
                {'name': 'Vacuum Cleaner', 'price': 1500, 'brand': 'Dyson', 'model_year': 2023}
            ],
            'Electronics': [
                {'name': 'Iphone 15 Pro Max', 'price': 50000, 'brand': 'Apple', 'model_year': 2024},
                {'name': 'Laptop', 'price': 30000, 'brand': 'Dell', 'model_year': 2023},
                {'name': 'Monitor', 'price': 90000, 'brand': 'LG', 'model_year': 2024},
                {'name': 'Camera', 'price': 35000, 'brand': 'Sony', 'model_year': 2023},
                {'name': 'Samsung Galaxy S24 Ultra', 'price': 55000, 'brand': 'Samsung', 'model_year': 2024}
            ],
            'Fashion': [
                {'name': 'T-shirt', 'price': 700, 'brand': 'Nike', 'model_year': 2024},
                {'name': 'Jeans', 'price': 1400, 'brand': 'Tommy', 'model_year': 2023},
                {'name': 'Jacket', 'price': 2000, 'brand': 'Adidas', 'model_year': 2024},
                {'name': 'Shoes', 'price': 2500, 'brand': 'Puma', 'model_year': 2023},
                {'name': 'Shorts', 'price': 1000, 'brand': 'Under Armour', 'model_year': 2024},
                {'name': 'Accessories', 'price': 400, 'brand': 'Gucci', 'model_year': 2023}
            ],
            'Books': [
                {'name': 'Python Programming', 'price': 500, 'author': 'John Doe', 'release_year': 2022},
                {'name': 'Data Science', 'price': 600, 'author': 'Jane Smith', 'release_year': 2023}
            ],
            'Sports': [
                {'name': 'Tennis Racket', 'price': 800, 'brand': 'Wilson', 'model_year': 2023},
                {'name': 'Football', 'price': 300, 'brand': 'Adidas', 'model_year': 2024}
            ]
        }

        self.sorted_items = {category: list(items) for category, items in self.items.items()}
        self.Category()
        self.root.mainloop()

    def Category(self):
        tk.Button(self.root, text="Home Appliances", font=("arial", 15),
                  command=lambda: self.open_category_page("Home Appliances")).place(x=10, y=10)
        tk.Button(self.root, text="Electronics", font=("arial", 15),
                  command=lambda: self.open_category_page("Electronics")).place(x=10, y=50)
        tk.Button(self.root, text="Fashion", font=("arial", 15),
                  command=lambda: self.open_category_page("Fashion")).place(x=10, y=90)
        tk.Button(self.root, text="Books", font=("arial", 15),
                  command=lambda: self.open_category_page("Books")).place(x=10, y=130)
        tk.Button(self.root, text="Sports", font=("arial", 15),
                  command=lambda: self.open_category_page("Sports")).place(x=10, y=170)
        tk.Button(self.root, text="Admin", font=("arial", 15),
                  command=self.open_admin_page).place(x=10, y=210)

    def open_category_page(self, category_name):
        for widget in self.root.winfo_children():
            widget.destroy()

        tk.Label(self.root, text=f"Welcome to the {category_name} Page", font=("arial", 20)).pack(pady=20)

        self.search_var = tk.StringVar()
        tk.Entry(self.root, textvariable=self.search_var, width=30).pack(pady=10)
        tk.Button(self.root, text="Search", command=lambda: self.search_items(category_name)).pack(pady=10)

        tk.Button(self.root, text="Sort Ascending",
                  command=lambda: self.sort_items(category_name, ascending=True)).pack(pady=10)
        tk.Button(self.root, text="Sort Descending",
                  command=lambda: self.sort_items(category_name, ascending=False)).pack(pady=10)

        tk.Button(self.root, text="Cart", command=self.open_cart_page).pack(pady=10)
        tk.Button(self.root, text="Back to Home", command=self.return_to_home).pack(pady=10)
        tk.Button(self.root, text="Add Items", command=self.open_admin_page).pack(pady=10)
        self.display_items(category_name)

    def search_items(self, category_name):
        search_term = self.search_var.get().strip().lower()
        items = self.sorted_items[category_name]

        result = self.binary_search(items, search_term)
        self.display_filtered_items(result)

    def binary_search(self, items, target_name):
        low, high = 0, len(items) - 1
        while low <= high:
            mid = (low + high) // 2
            mid_name = items[mid]['name'].lower()
            if mid_name == target_name:
                return [items[mid]]
            elif mid_name < target_name:
                low = mid + 1
            else:
                high = mid - 1
        return []

    def sort_items(self, category_name, ascending=True):
        items = self.items[category_name]
        self.quick_sort(items, 0, len(items) - 1, ascending)
        self.sorted_items[category_name] = sorted(items, key=lambda x: x['price'],
                                                  reverse=not ascending)
        self.display_items(category_name)

    def quick_sort(self, items, low, high, ascending=True):
        if low < high:
            pi = self.partition(items, low, high, ascending)
            self.quick_sort(items, low, pi - 1, ascending)
            self.quick_sort(items, pi + 1, high, ascending)

    def partition(self, items, low, high, ascending=True):
        pivot = items[high]['price']
        i = low - 1
        for j in range(low, high):
            if (items[j]['price'] <= pivot) if ascending else (items[j]['price'] >= pivot):
                i += 1
                items[i], items[j] = items[j], items[i]
        items[i + 1], items[high] = items[high], items[i + 1]
        return i + 1

    def display_items(self, category_name):
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.Label) and widget.cget("text").startswith("Name:"):
                widget.destroy()
        for item in self.sorted_items[category_name]:
            tk.Label(self.root, text=f"Name: {item['name']}, Price: {item['price']}").pack()

    def display_filtered_items(self, items):
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.Label) and widget.cget("text").startswith("Name:"):
                widget.destroy()
        if items:
            for item in items:
                tk.Label(self.root, text=f"Name: {item['name']}, Price: {item['price']}").pack()
        else:
            tk.Label(self.root, text="No items found").pack()

    def return_to_home(self):
        for widget in self.root.winfo_children():
            widget.destroy()

        self.Category()
 def open_admin_page(self):
        for widget in self.root.winfo_children():
            widget.destroy()

        tk.Label(self.root, text="Admin Page", font=("arial", 20)).pack(pady=20)

        self.admin_category_var = tk.StringVar()
        tk.Label(self.root, text="Select a Category:").pack(pady=5)
        category_menu = tk.OptionMenu(self.root, self.admin_category_var, *self.items.keys())
        category_menu.pack(pady=5)



        tk.Label(self.root, text="Remove Product:", font=("arial", 15)).pack(pady=20)
        self.remove_product_var = tk.StringVar()
        tk.Label(self.root, text="Product Name:").pack(pady=5)
        tk.Entry(self.root, textvariable=self.remove_product_var).pack(pady=5)
        tk.Button(self.root, text="Remove Product", command=self.remove_product).pack(pady=10)

        tk.Label(self.root, text="Add New Product:", font=("arial", 15)).pack(pady=20)
        self.admin_name_var = tk.StringVar()
        tk.Label(self.root, text="Product Name:").pack(pady=5)
        tk.Entry(self.root, textvariable=self.admin_name_var).pack(pady=5)
        self.admin_price_var = tk.DoubleVar()
        tk.Label(self.root, text="Product Price:").pack(pady=5)
        tk.Entry(self.root, textvariable=self.admin_price_var).pack(pady=5)
        tk.Button(self.root, text="Add Product", command=self.add_product).pack(pady=10)

        tk.Button(self.root, text="Back to Home", command=self.return_to_home).pack(pady=10)



    def display_admin_products(self, category_name):
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.Label) and widget.cget("text").startswith("Name:"):
                widget.destroy()
        for item in self.items[category_name]:
            tk.Label(self.root, text=f"Name: {item['name']}, Price: {item['price']}").pack()

    def add_product(self):
        category_name = self.admin_category_var.get()
        item_name = self.admin_name_var.get().strip()
        item_price = self.admin_price_var.get()

        if not category_name or not item_name or item_price <= 0:
            messagebox.showwarning("Warning", "Invalid product details")
            return

        new_item = {"name": item_name, "price": item_price}
        self.items[category_name].append(new_item)
        self.sorted_items[category_name] = sorted(self.items[category_name],
                                                  key=lambda x: x['price'])
        self.display_admin_products(category_name)
        messagebox.showinfo("Success", "Product added successfully")

    def remove_product(self):
        category_name = self.admin_category_var.get()
        product_name = self.remove_product_var.get().strip()

        if not category_name or not product_name:
            messagebox.showwarning("Warning", "Please enter the product name and select a category")
            return

        items = self.items[category_name]
        self.items[category_name] = [item for item in items if item['name'].lower() != product_name.lower()]
        self.sorted_items[category_name] = sorted(self.items[category_name],
                                                  key=lambda x: x['price'])
        self.display_admin_products(category_name)
        messagebox.showinfo("Success", "Product removed successfully")


Categories()
class Categories:
    def __init__(self, root, category_name, go_back_callback):
        self.page_stack = []
        self.root = root
        self.go_back_callback = go_back_callback
        self.root.title("Category Selection")
        self.root.geometry("500x500")
        self.items = self.load_items()
        self.sorted_items = {category: list(items) for category, items in self.items.items()}
        self.cart = {}
        self.open_category_page(category_name)

    def go_back(self):
        if len(self.page_stack) > 1:
            self.page_stack.pop()
            previous_page = self.page_stack[-1]
            if previous_page == "Main Categories":
                self.load_main_page()
            else:
                self.load_page(previous_page, from_back=True)
        else:
            self.go_back_callback()

    def load_items(self):
        with open('items.json', 'r') as file:
            return json.load(file)

    def save_items(self):
        with open('items.json', 'w') as file:
            json.dump(self.items, file, indent=4)

    def open_category_page(self, category_name):
        for widget in self.root.winfo_children():
            widget.destroy()

        tk.Label(self.root, text=f"Welcome to the {category_name} Page", font=("arial", 20)).pack(pady=20)

        self.search_var = tk.StringVar()
        tk.Entry(self.root, textvariable=self.search_var, width=30).pack(pady=10)
        tk.Button(self.root, text="Search", command=lambda: self.search_items(category_name)).pack(pady=10)

        tk.Button(self.root, text="Sort Ascending",
                  command=lambda: self.sort_items(category_name, ascending=True)).pack(pady=10)
        tk.Button(self.root, text="Sort Descending",
                  command=lambda: self.sort_items(category_name, ascending=False)).pack(pady=10)


        tk.Button(self.root, text="Back to Home", command=self.return_to_home).pack(pady=10)
        tk.Button(self.root, text="Proceed to Checkout", command=self.open_cart_page).pack(pady=10)

        self.display_items(category_name)

    def search_items(self, category_name):
        search_term = self.search_var.get().strip().lower()
        items = self.sorted_items[category_name]
        filtered_items = [item for item in items if search_term in item['name'].lower()]
        self.display_filtered_items(filtered_items)

    def display_filtered_items(self, items):
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.Frame):
                widget.destroy()
        self.display_items_content(items)

    def sort_items(self, category_name, ascending=True):
        items = self.items[category_name]
        sorted_items = sorted(items, key=lambda x: x['price'], reverse=not ascending)
        self.sorted_items[category_name] = sorted_items
        self.display_items(category_name)

    def display_items(self, category_name):
        items = self.sorted_items[category_name]
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.Frame):
                widget.destroy()
        self.display_items_content(items)

    def display_items_content(self, items):
        for item in items:
            item_frame = tk.Frame(self.root)
            item_frame.pack(pady=5)
            item_label = tk.Label(item_frame, text=f"Name: {item['name']}, Price: {item['price']}")
            item_label.pack(side="left", padx=5)
            qty_var = tk.IntVar(value=0)
            qty_spinbox = tk.Spinbox(item_frame, from_=0, to=100, textvariable=qty_var)
            qty_spinbox.pack(side="left", padx=5)
            add_button = tk.Button(item_frame, text="Add to Cart", command=lambda i=item, q=qty_var: self.add_to_cart(i, q))
            add_button.pack(side="left", padx=5)

    def add_to_cart(self, item, qty_var):
        quantity = qty_var.get()
        userid=qty_var
        if quantity > 0:
            x=self.cart[item['name']] = {'price': item['price'], 'quantity': quantity}
            js = handel_file_json()
            js.adde("Cart", x)

            messagebox.showinfo("Cart", f"Added {quantity} of {item['name']} to cart!")
        else:
            messagebox.showwarning("Quantity Error", "Please select a valid quantity.")

    def open_cart_page(self):
        for widget in self.root.winfo_children():
            widget.destroy()



        tk.Label(self.root, text="This is the Cart Page", font=("arial", 20)).pack(pady=20)


        if self.cart:
            for item_name, details in self.cart.items():
                tk.Label(self.root, text=f"{item_name}: {details['quantity']} @ ${details['price']} each").pack()
            total_price = sum(details['price'] * details['quantity'] for details in self.cart.values())
            tk.Label(self.root, text=f"Total Price: ${total_price}").pack(pady=10)
        else:
            tk.Label(self.root, text="You have not selected any products.").pack(pady=10)

        tk.Button(self.root, text="Back to Home", command=self.return_to_home).pack(pady=10)

    def return_to_home(self):
        self.root.destroy()
        import itemPage
        root = tk.Tk()
        itemPage.itemsPage(root, lambda: root.destroy())
Leave a Comment