Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
4.7 kB
0
Indexable
Never
import csv
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import font
import os, sys

class ProductApp:
    def __init__(self, root):
        self.root = root
        self.product_data = {}
        self.root.title('Product List')
        
        # Set a default font to make the text larger
        default_font = font.nametofont("TkDefaultFont")
        default_font.configure(size=12)
        self.root.option_add("*Font", default_font)
        
        self.load_data()
        self.create_widgets()

    def load_data(self):
        try: # running using executable
            path = sys._MEIPASS
        except: # running using .py sript
            path = os.path.abspath('.')
        csv_path = os.path.join(path, 'products.csv')
        try:
            with open(csv_path, newline='', mode='r') as csvfile:
                reader = csv.DictReader(csvfile)
                for row in reader:
                    self.product_data[row['Code']] = {'Name': row['Name'], 'Price': float(row['Price'])}
        except FileNotFoundError:
            messagebox.showerror("Error", "The file 'products.csv' does not exist.")
        except Exception as e:
            messagebox.showerror("Error", str(e))

    def create_widgets(self):
        self.form_frame = tk.Frame(self.root)
        self.form_frame.pack(fill='x')

        tk.Label(self.form_frame, text='Code:').pack(side='left', padx=(10, 10))
        
        self.product_code = tk.Entry(self.form_frame)
        self.product_code.pack(side='left', expand=True, padx=(0, 10))
        
        self.add_button = tk.Button(self.form_frame, text='Add Product', command=self.add_product)
        self.add_button.pack(side='left', padx=(0, 10))

        # Bind the Return key to the add_product method
        self.root.bind('<Return>', lambda event: self.add_product())
        
        self.tree = ttk.Treeview(self.root, columns=('Code', 'Name', 'Price', 'Delete'), show='headings')
        self.tree.heading('Code', text='Code')
        self.tree.heading('Name', text='Name')
        self.tree.heading('Price', text='Price')
        self.tree.heading('Delete', text='Delete')

        self.tree.column('Code', width=100, anchor='center')
        self.tree.column('Name', width=200, anchor='center')
        self.tree.column('Price', width=100, anchor='center')
        self.tree.column('Delete', width=50, anchor='center')

        self.tree.pack(fill='both', expand=True)
        self.tree.bind('<ButtonRelease-1>', self.on_item_select)

        self.root.bind('<space>', self.clear_all_products)
        
        self.total_label = tk.Label(self.root, text='Total Price: $0.00')
        self.total_label.pack(side='bottom', fill='x')
        
        self.update_total_price()

    def update_total_price(self):
        total_price = sum(float(self.tree.item(child)["values"][2]) for child in self.tree.get_children())
        self.total_label.config(text=f'Total Price: ${total_price:.2f}')

    def on_item_select(self, event):
        region = self.tree.identify('region', event.x, event.y)
        col = self.tree.identify_column(event.x)
        selected_item = self.tree.selection()[0]
        if region == 'cell' and col == '#4':
            self.tree.delete(selected_item)
            self.update_total_price()

    def add_product(self):
        code = self.product_code.get().strip()
        if code in self.product_data:
            if not self.product_in_treeview(code):
                product = self.product_data[code]
                self.tree.insert('', 'end', values=(code, product['Name'], product['Price'], 'Delete'))
                self.update_total_price()
                self.product_code.delete(0, tk.END)
            else:
                messagebox.showwarning("Warning", f"Product with code {code} is already listed.")
        else:
            messagebox.showerror("Error", "Product code does not exist.")

    def product_in_treeview(self, code):
        for child in self.tree.get_children():
            if self.tree.item(child)["values"][0] == code:
                return True
        return False
    
    def clear_all_products(self, event=None):
        for child in self.tree.get_children():
            self.tree.delete(child)
        self.update_total_price()


def main():
    root = tk.Tk()
    app = ProductApp(root)
    root.geometry("600x400")  # Increase the size to accommodate larger text
    root.mainloop()


if __name__ == "__main__":
    main()




Code,Name,Price
001,Product 1,19.99
002,Product 2,29.99
003,Product 3,14.99
004,Product 4,24.99
005,Product 5,39.99
006,Product 6,9.99
007,Product 7,49.99
008,Product 8,34.99
009,Product 9,17.99
010,Product 10,27.99
Leave a Comment