-
Notifications
You must be signed in to change notification settings - Fork 0
/
products.py
70 lines (60 loc) · 2.36 KB
/
products.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from helpers import clean_screen
from canvas import tk
from tkinter import Button, Label
from tkinter.ttk import *
import json
import os
base_folder = os.path.dirname(__file__)
def render_products():
clean_screen()
row = 0
col = 0
max = 4
with open("db/products.txt", "r") as file:
products = file.readlines()
for line in products:
product = json.loads(line[:-1] if "\n" in line else line)
if col == max:
row = 0
col = 0
row += 1
Label(tk, text=product["name"]).grid(row=row+1, column=col, pady=2)
from PIL import Image, ImageTk
# Create the PIL image object
image = Image.open(os.path.join(os.path.join(base_folder, "images"), product["img_path"]))
image = image.resize((100, 100))
photo = ImageTk.PhotoImage(image)
img_label = Label(image=photo)
img_label.image = photo
img_label.grid(row=row+2, column=col)
Label(tk, text=product["count"]).grid(row=row+3, column=col, pady = 2)
button = Button(tk, text=f"Buy {product['id']}")
button.configure(command=lambda b=button: buy_product(b))
button.grid(row=row+4, column=col)
col += 1
def update_product_quantity(product_id):
with open("db/products.txt", "r+") as file:
products = file.readlines()
file.seek(0)
for line in products:
current_product = json.loads(line[:-1])
if current_product["id"] == product_id:
current_product["count"] -= 1
file.write(json.dumps(current_product) + "\n")
def buy_product(button):
_, product_id = button.cget("text").split()
product_id = int(product_id)
username = None
with open("db/current_user.txt", "r", ) as file:
username = file.readline()
if username:
with open("db/users.txt", "r+", newline="\n") as users_file:
data = users_file.readlines()
users_file.seek(0)
for line in data:
current_user = json.loads(line[:-1])
if current_user["username"] == username:
current_user["products"].append(product_id)
users_file.write(json.dumps(current_user) + "\n")
update_product_quantity(product_id)
render_products()