Add/Edit Product

root = tk.Toplevel() #Create window at top level
root.title("Add/Edit Product") #Give title to window
root.configure(bg="#585858") #Set Background Color
root.resizable(width=0, height=0)
win_width = 1280
win_height = int(1280 * 56.25 / 100)
root.geometry(str(win_width) + "x" + str(win_height))
# Get screen size
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
self.width = win_width * 96 / 100
self.height = win_height * 94 / 100
After creation of window, we will add a canvas background.
bg_canvas = RoundBackgroundFrame(root, self.width, self.height, padding, cornerradius, self.color, "#585858")
bg_canvas.place(width=self.width, height=self.height, x=win_width / 2 - self.width / 2,y=win_height / 2 - self.height / 2)
class RoundBackgroundFrame(tk.Canvas):
def __init__(self, parent, width, height, padding, cornerradius, color, bg):
tk.Canvas.__init__(self, parent, borderwidth=0, relief="flat", highlightthickness=0, bg=bg)
original = Image.open("images/corner.png")
resized = original.resize((int(40), int(40)), Image.ANTIALIAS)
self.image_r_t = ImageTk.PhotoImage(resized)
original = original.rotate(90, expand=0)
resized = original.resize((int(40), int(40)), Image.ANTIALIAS)
self.image_l_t = ImageTk.PhotoImage(resized)
original = original.rotate(90, expand=0)
resized = original.resize((int(40), int(40)), Image.ANTIALIAS)
self.image_l_b = ImageTk.PhotoImage(resized)
original = original.rotate(90, expand=0)
resized = original.resize((int(40), int(40)), Image.ANTIALIAS)
self.image_r_b = ImageTk.PhotoImage(resized)
self.shape(width, height, padding, cornerradius, color)
(x0, y0, x1, y1) = self.bbox("all")
width = (x1 - x0)
height = (y1 - y0)
self.configure(width=width, height=height)
def shape(self, width, height, padding, cornerradius, color):
self.create_polygon((padding, height - cornerradius - padding, padding, cornerradius + padding,
padding + cornerradius, padding, width - padding - cornerradius, padding,
width - padding, cornerradius + padding, width - padding,
height - cornerradius - padding, width - padding - cornerradius, height - padding,
padding + cornerradius, height - padding), fill=color, outline=color)
self.create_image(width - self.image_r_t.width(), 0, image=self.image_r_t, anchor=NW)
self.create_image(0, 0, image=self.image_l_t, anchor=NW)
self.create_image(0, height - self.image_l_b.width(), image=self.image_l_b, anchor=NW)
self.create_image(width - self.image_r_b.width(), height - self.image_r_b.width(), image=self.image_r_b,anchor=NW)
self.width = self.width * 98 / 100
self.height = self.height * 96 / 100
self.base_frame = Frame(root, width=self.width, height=self.height, bg=self.color)
bg_canvas.create_window(self.width / 100, self.height * 2 / 100, anchor=NW, window=self.base_frame)
# Add Heading Name
add_heading_label(self.base_frame, self.color, AppConstant.FONT_SIZE, self.height, self.width)
def add_heading_label(base_frame, color, font_size, height, width):
label_heading = Label(base_frame, text="Add/Edit Product", anchor=CENTER, bg=color, font=("Lucida Grande", font_size + 6))
label_heading.place(width=width * 90 / 100, height=height * 7 / 100, x=width * 5 / 100, y=height * 0.5 / 100)
# Add line
add_line_border(self.base_frame, self.color, self.height, self.width)
def add_line_border(base_frame, color, height, width):
line_canvas = Canvas(base_frame, bg=color, borderwidth=0, relief="flat", highlightthickness=0)
line_canvas.place(width=width - 4, height=5, x=2, y=height * 10 / 100)
line_canvas.create_line(0, 0, width, 0, fill="#787878")
button_font = add_action_frame(self.base_frame, self.color, self.height, self.width)
def add_action_frame(base_frame, color, height, width):
afw = width * 0.35
afh = height * 0.87
button_font = ("Lucida Grande", AppConstant.FONT_SIZE - 6)
label_frame_action = LabelFrame(base_frame, text="Actions", font=button_font, pady=afw * 2 / 100,
padx=afw * 2 / 100, bg=color)
label_frame_action.place(width=afw, height=afh, x=0, y=height * 0.12)
return button_font
add_search_frame(self.base_frame, button_font, self.color, self.height, self.width)
def add_search_frame(base_frame, button_font, color, height, width):
sfw = width * 0.638
sfh = height * 0.87
label_frame_search = LabelFrame(base_frame, text="Search", font=button_font, pady=sfw * 2 / 100,
padx=sfw * 2 / 100, bg=color)
label_frame_search.place(width=sfw, height=sfh, x=width * 0.36, y=height * 0.12)
# Add Product UI
self.product_name = CustomEntrySimple(self.base_frame, 300, 60, ("Lucida Grande", AppConstant.FONT_SIZE - 6), self.color, "Product Name")
self.product_name.place(x=50, y=150)
self.product_category = CustomEntrySimple(self.base_frame, 300, 60, ("Lucida Grande", AppConstant.FONT_SIZE - 6), self.color,"product Name")
self.product_category.place(x=50, y=230)
self.product_price = CustomEntrySimple(self.base_frame, 300, 60, ("Lucida Grande", AppConstant.FONT_SIZE - 6), self.color, "Product Price in Rs")
self.product_price.place(x=50, y=310)
self.product_count = CustomEntrySimple(self.base_frame, 300, 60, ("Lucida Grande", AppConstant.FONT_SIZE - 6), self.color, "Product Quantity")
self.product_count.place(x=50, y=390)
self.product_gst = CustomEntrySimple(self.base_frame, 300, 60, ("Lucida Grande", AppConstant.FONT_SIZE - 6), self.color, "Product Gst")
self.product_gst.place(x=50, y=470)
Here is our class CustomEntrySimple:
class CustomEntrySimple(tk.Canvas):
def __init__(self, parent, width, height, font, color, text):
tk.Canvas.__init__(self, parent, borderwidth=0, relief="flat", highlightthickness=0, bg=color)
self.width = width
self.height = height
self.color = color
self.create_text(6, 5, anchor=W, font=font, text=text, fill="#000000")
self.create_line(5, height - 8, width - 5, height - 8, fill="#808080")
frame = Frame(parent,width=width * 95 / 100, height=height * 50 / 100)
self.entry = Entry(frame, bg=color, bd=0, highlightthickness=0, font=font)
self.entry.place(relwidth=1, relheight=1, x=0, y=0)
self.create_window(6, height / 2 - (height * 50 / 100) / 2, anchor=NW, window=frame)
self.update()
(x0, y0, x1, y1) = self.bbox("all")
width = (x1 - x0)
height = (y1 - y0)
self.configure(width=width, height=height)
Create a "Submit" button and show it.
def show_add_product_button(self):
self.add_button = RoundedButton(self.base_frame, 250, 130 / 2.56, self.color, "images/button3.png",
"ADD product",
font=("Lucida Grande", AppConstant.FONT_SIZE - 2),
command=self.add_product_click)
self.add_button.place(x=75, y=self.height * 0.87)
self.show_add_product_button()
self.ce_book_var = CustomEntry(self.base_frame, 300, 55, 10, 2, self.color, "Search Product",
"images/ic_search.png")
self.ce_book_var.place(x=self.width / 2 - 150, y=self.height * 0.20)
self.ce_book_var.entry.bind('', self.search_product)
Here's the logic to search data in table
def search_product(self, *arg):
self.hide_edit_button()
if self.ce_product_var.entry.get() != "":
self.tree.delete(*self.tree.get_children())
conn = Util.connect_db()
cursor = conn.cursor()
cursor.execute(
"SELECT product_id, product_name, product_category, product_count, product_price,product_gst FROM `product` WHERE `product_name` LIKE ? OR `product_id` LIKE ?",
('%' + str(self.ce_product_var.entry.get()) + '%',
'%' + str(self.ce_product_var.entry.get()) + '%'))
fetch = cursor.fetchall()
count = 0
for data in fetch:
if count % 2 == 0:
self.tree.insert('', 'end', values=data, tags=('even',))
else:
self.tree.insert('', 'end', values=data, tags=('odd',))
count = count + 1
cursor.close()
conn.close()
else:
self.reset_product()
def reset_product(self):
self.tree.delete(*self.tree.get_children())
self.update_table_data()
class Util:
@staticmethod
def connect_db():
db = None
try:
db = sql.connect("inventry.db")
return db
except sql.Error as error:
print("Failed to insert data into sqlite table", error)
Fetch data from database and show it in table form with the use of "Treeview" of Tkinter.
db = Util.connect_db()
cursor = db.cursor()
cursor.execute('SELECT product_id, product_name, product_category, product_count, product_price,product_gst FROM product')
self.sql_output = cursor.fetchall()
style = ttk.Style()
style.element_create("Custom.Treeheading.border", "from", "default")
style.layout("Custom.Treeview.Heading", [
("Custom.Treeheading.cell", {'sticky': 'nswe'}),
("Custom.Treeheading.border", {'sticky': 'nswe', 'children': [
("Custom.Treeheading.padding", {'sticky': 'nswe', 'children': [
("Custom.Treeheading.image", {'side': 'right', 'sticky': ''}),
("Custom.Treeheading.text", {'sticky': 'we'})
]})
]}),
])
# style.configure("Custom.Treeview.Heading", background="blue", foreground="red", relief="flat")
style.map("Custom.Treeview.Heading", relief=[('active', 'groove'), ('pressed', 'sunken')])
style.configure("Custom.Treeview", highlightthickness=0, bd=0, font=('Calibri', 11), rowheight=30)
self.tree = ttk.Treeview(self.base_frame, height=13, show='tree', style="Custom.Treeview")
self.tree.tag_configure('odd', background='#d9edcb', foreground="#000000", )
self.tree.tag_configure('even', background='#FFFFFF', foreground="#000000", )
self.tree.place(x=self.width / 2 - 158, y=230)
self.tree["columns"] = "1", "2", "3", "4", "5","6"
self.tree.column("#0", width=0)
self.tree.column("#1", width=70)
self.tree.column("#3", width=120)
self.tree.column("#4", width=120)
self.tree.column("#5", width=120)
self.tree.column("#6", width=100)
self.table_heading()
vsby = ttk.Scrollbar(self.base_frame, orient="vertical", command=self.tree.yview)
vsby.place(x=self.width - 24, y=230, height=390)
self.tree.configure(yscrollcommand=vsby.set)
self.update_table_data()
self.tree.column("#1", anchor=tk.CENTER)
self.tree.column("#2", anchor=tk.CENTER)
self.tree.column("#3", anchor=tk.CENTER)
self.tree.column("#4", anchor=tk.CENTER)
self.tree.column("#5", anchor=tk.CENTER)
self.tree.bind('<>', self.on_tree_click)
self.root.attributes('-alpha', 0.0)
Util.center(self.root)
self.root.attributes('-alpha', 1.0)
We have created our own heading for table, lets configure it.
def table_heading(self):
heading_y = 200
bg_color = "#618645"
text_color = "#ffffff"
canvas = Canvas(self.base_frame, width=735, height=30)
canvas.create_rectangle(0, 0, 790, 30, fill=bg_color)
canvas.place(x=self.width / 2 - 160, y=heading_y - 3)
product_id_label = ttk.Label(self.base_frame, text="product Id",
font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
foreground=text_color)
product_id_label.place(width=120,x=self.width / 2 - 152, y=heading_y)
product_id_label.configure(anchor="center")
product_name_label = ttk.Label(self.base_frame, text="Name",
font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
foreground=text_color)
product_name_label.place(width=120,x=self.width / 2 -20, y=heading_y)
product_name_label.configure(anchor="center")
product_category_label = ttk.Label(self.base_frame, text="Category",
font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
foreground=text_color)
product_category_label.place(width=120,x=self.width / 2 + 130, y=heading_y)
product_category_label.configure(anchor="center")
product_Count = ttk.Label(self.base_frame, text="Count",
font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
foreground=text_color)
product_Count.place(width=120,x=self.width / 2 + 250, y=heading_y)
product_Count.configure(anchor="center")
product_Price = ttk.Label(self.base_frame, text="Price",
font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
foreground=text_color)
product_Price.place(width=120,x=self.width / 2 + 370, y=heading_y)
product_Price.configure(anchor="center")
product_Gst = ttk.Label(self.base_frame, text="Gst",
font=('Calibri', AppConstant.FONT_SIZE - 3, 'bold'), background=bg_color,
foreground=text_color)
product_Gst.place(width=50,x=self.width / 2 + 475, y=heading_y)
product_Gst.configure(anchor="center")
UI part is completed, lets move to funtionality. First we need to add click on "Add Product" button.
def add_product_click(self):
var = ""
product_name = ""
product_Category_name = ""
product_price = ""
product_total_count = ""
product_gst=""
is_name_entered = False
is_category_name_entered = False
is_price_entered = False
is_product_total_count_entered = False
is_prduct_gst_entered=False
if self.product_count.entry.get() == "" or self.product_count.entry.get() == " ":
var += "product Count Should not be empty, "
else:
product_total_count = self.product_count.entry.get()
is_product_total_count_entered = True
if self.product_name.entry.get() == "" or self.product_name.entry.get() == " ":
var += "product Name Should not be empty, "
else:
product_name = self.product_name.entry.get()
is_name_entered = True
if self.product_category.entry.get() == "" or self.product_category.entry.get() == " ":
var += "Author Name Should not be empty, "
else:
product_Category_name = self.product_category.entry.get()
is_category_name_entered = True
if self.product_price.entry.get() == "" or self.product_price.entry.get() == " ":
var += "product Price Should not be empty, "
else:
product_price = self.product_price.entry.get()
is_price_entered = True
if self.product_gst.entry.get() == "" or self.product_gst.entry.get() == " ":
var += "product GST Should not be empty, "
else:
product_gst = self.product_gst.entry.get()
is_prduct_gst_entered = True
if is_name_entered and is_price_entered and is_category_name_entered and is_prduct_gst_entered and is_product_total_count_entered:
conn = Util.connect_db()
cursor = conn.cursor()
key = "PRODUCT_LAST_COUNT"
cursor.execute('SELECT value FROM system_INFO WHERE key IS ?', (key,))
rows = cursor.fetchone()
print(rows[0])
id_count = Util.convert_string_to_int(rows[0]) + 1
product_id = get_product_id(id_count) + str(id_count)
cursor.execute(
'INSERT INTO product(product_id, product_name, product_category, product_price, product_count,product_gst) VALUES(?,?,?,?,?,?)',
(product_id, product_name, product_Category_name,product_price, product_total_count, product_gst))
conn.commit()
messagebox.showinfo("Success", "product has been added successfully")
self.product_price.entry.delete(0, 'end')
self.product_category.entry.delete(0, 'end')
self.product_name.entry.delete(0, 'end')
self.product_price.entry.delete(0, 'end')
self.product_count.entry.delete(0, 'end')
self.product_gst.entry.delete(0, 'end')
self.product_name.entry.focus()
cursor.execute("UPDATE system_info SET value = ? WHERE key = ?",
(id_count, key,))
conn.commit()
self.tree.delete(*self.tree.get_children())
self.update_table_data()
else:
print(var)
messagebox.showerror("showerror", var)
def update_table_data(self):
conn = Util.connect_db()
cursor = conn.cursor()
cursor.execute('SELECT product_id, product_name, product_category, product_count, product_price,product_gst FROM product')
self.sql_output = cursor.fetchall()
count = 0
for data in self.sql_output:
if count % 2 == 0:
self.tree.insert('', 'end', values=data, tags=('even',))
else:
self.tree.insert('', 'end', values=data, tags=('odd',))
count = count + 1
To edit and delete Product on click on table row, we need to show Edit And Delete Button.
def on_tree_click(self, *args):
self.show_edit_button()
self.show_delete_button()
def show_delete_button(self, *args):
self.delete_button = RoundedButton(self.base_frame, 110, 130 / 3.75, self.color, "images/button3.png",
"DELETE",
font=("Lucida Grande", AppConstant.FONT_SIZE - 4),
command=self.delete_product)
self.delete_button.place(x=self.width / 2 + 420, y=self.height * 0.20)
def delete_product(self):
cur_item = self.tree.focus()
product_id = self.tree.item(cur_item)["values"][0]
product_name = self.tree.item(cur_item)["values"][1]
response = messagebox.askokcancel("Are you sure?", "Do you want to delete " + product_name + " ?")
if response:
conn = Util.connect_db()
cursor = conn.cursor()
cursor.execute("DELETE FROM product WHERE product_number = ?", (product_id,))
conn.commit()
self.tree.delete(*self.tree.get_children())
self.update_table_data()
def edit_product(self):
cur_item = self.tree.focus()
self.product_name.entry.delete(0, END)
self.product_category.entry.delete(0, END)
self.product_price.entry.delete(0, END)
self.product_price.entry.delete(0, END)
self.product_count.entry.delete(0, END)
self.product_gst.entry.delete(0, END)
self.product_name.entry.insert(0, self.tree.item(cur_item)["values"][1])
self.product_category.entry.insert(0, self.tree.item(cur_item)["values"][2])
self.product_price.entry.insert(0, self.tree.item(cur_item)["values"][4])
self.product_count.entry.insert(0, self.tree.item(cur_item)["values"][3])
self.product_gst.entry.insert(0, self.tree.item(cur_item)["values"][5])
self.add_button.place_forget()
product_id = self.tree.item(cur_item)["values"][0]
self.hide_edit_button()
self.update_button = RoundedButton(self.base_frame, 170, 130 / 2.56, self.color, "images/button3.png", "UPDATE",
font=("Lucida Grande", AppConstant.FONT_SIZE - 2),
command=lambda: self.update_product_click(product_id))
self.update_button.place(x=25, y=self.height * 0.87)
self.cancel_button = RoundedButton(self.base_frame, 170, 130 / 2.56, self.color, "images/button3.png", "CANCEL",
font=("Lucida Grande", AppConstant.FONT_SIZE - 2),
command=self.cancel_button_click)
self.cancel_button.place(x=220, y=self.height * 0.87)
Implement Update And Cancel Button functionality
def update_product_click(self, student_id):
var = ""
product_name = ""
product_category = ""
product_price = ""
product_total_count = ""
product_gst=""
is_name_entered = False
is_author_name_entered = False
is_price_entered = False
is_product_total_count_entered = False
is_product_gst_entered=False
if self.product_count.entry.get() == "" or self.product_count.entry.get() == " ":
var += "product Count Should not be empty, "
else:
product_total_count = self.product_count.entry.get()
is_product_total_count_entered = True
if self.product_name.entry.get() == "" or self.product_name.entry.get() == " ":
var += "product Name Should not be empty, "
else:
product_name = self.product_name.entry.get()
is_name_entered = True
if self.product_category.entry.get() == "" or self.product_category.entry.get() == " ":
var += "Author Name Should not be empty, "
else:
product_category = self.product_category.entry.get()
is_author_name_entered = True
if self.product_price.entry.get() == "" or self.product_price.entry.get() == " ":
var += "product Price Should not be empty, "
else:
product_price = self.product_price.entry.get()
is_price_entered = True
if self.product_gst.entry.get() == "" or self.product_gst.entry.get() == " ":
var += "product Gst Should not be empty, "
else:
product_gst = self.product_gst.entry.get()
is_product_gst_entered = True
if is_name_entered and is_price_entered and is_author_name_entered and is_product_total_count_entered and is_product_gst_entered:
conn = Util.connect_db()
cursor = conn.cursor()
cursor.execute(
"UPDATE product SET product_name = ?, product_category = ?, product_price = ?, product_count = ?, product_gst = ? WHERE product_id = ?",
(product_name, product_category, product_price, product_total_count, product_gst, student_id,))
conn.commit()
self.product_price.entry.delete(0, 'end')
self.product_category.entry.delete(0, 'end')
self.product_name.entry.delete(0, 'end')
self.product_price.entry.delete(0, 'end')
self.product_count.entry.delete(0, 'end')
self.product_gst.entry.delete(0, 'end')
messagebox.showinfo("Success", "product detail has been updated successfully")
self.tree.delete(*self.tree.get_children())
self.update_table_data()
self.show_add_product_button()
self.hide_edit_button()
self.cancel_button.place_forget()
self.update_button.place_forget()
At last we will manage closing of window
def on_closing():
root.destroy()
args[0].deiconify()
root.protocol("WM_DELETE_WINDOW", on_closing)
Programmer Mirta is for learning and training. Projects might be simple to improve learning. Projects are constantly reviewed to avoid errors, but we cannot assure full correctness of all content. While using Programmer Mitra, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2021 by Programmer Mitra. All Rights Reserved.