from tkinter import ttk
from tkinter import *
import sqlite3
# ------------- APLICACION DE PRODUCTOS--------------
# 1 - CREACION CLASE PRODUCT PARA MANEJAR TODAS LAS VENTANAS Y METODOS DE LA APLICACION DE PRODUCTOS
class Product:
# 8 - CREAR VARIABLE PARA BD
db_name = 'database.db'
# 4 - DEFINIMOS EL CONSTRUCTOR Y TOMAMOS EL PARAMETRO QUE NOS ESTAN PASANDO AL INICIAR LA VENTANA
def __init__(self, window):
# 6 - CREAR PROPIEDAD U OBJETO PARA ALMACENAR LA VENTANA QUE ESTA RECIBIENDO EL CONSTRUCTOR
self.win = window
style = ttk.Style()
self.win.title('Aplicacion de Productos')
# 7 - CREACION INTERFAZ GRAFICA
# FRAME CONTENEDOR
frame = LabelFrame(self.win, text=' REGISTRAR UN NUEVO PRODUCTO: ')
frame.gridinterfaz_inicial(row = 0, column = 0, columnspan = 3, pady = 15, ipadx = 5, ipady = 5)
# INPUT NAME
Label(frame, text=' Nombre: ').grid(row = 1, column = 0, padx = 20, pady = 5, sticky = W)
self.name = Entry(frame, width=45)
self.name.focus()
self.name.grid(row = 1, column = 1, sticky = W)
# INPUT PRECIO
Label(frame, text=' Precio: ').grid(row = 2, column = 0, padx = 20, pady = 5, sticky = W)
self.price = Entry(frame, width=25)
self.price.grid(row = 2, column = 1, sticky = W)
# INPUT STOCK
Label(frame, text=' Stock: ').grid(row = 3, column = 0, padx = 20, pady = 5, sticky = W)
self.stock = Entry(frame, width=25)
self.stock.grid(row = 3, column = 1, sticky = W)
# INPUT SECCION
Label(frame, text=' Seccion: ').grid(row = 4, column = 0, padx = 20, pady = 5, sticky = W)
self.section = Entry(frame, width=45)
self.section.grid(row = 4, column = 1, sticky = W)
# BOTON AGREGAR PRODUCTO
style = ttk.Style ()
style.configure('TButton', font = ('calibri', 10, 'bold', 'underline'), background = '#cbe5fe', foreground = 'red')
ttk.Button(frame, text='Agregar Producto', style =text='AGREGAR 'TButton'PRODUCTO', command=self.add_product).grid(row = 5, columnspan = 2, padx=5ipadx=40, pady = 10, sticky = W + E)
# LABEL PARA MENSAJES DE SALIDA
self.message = Label(text = '')
self.message.grid(row = 6, column = 0, columnspan = 5, sticky = W + E, padx = 150)
# TABLA
frame2 = LabelFrame(self.win, text=' LISTADO DE PRODUCTOS: ')
frame2.grid(row = 7, column = 0, columnspan = 3, padx = 20, pady = 15)
self.tree = ttk.Treeview(frame2, height = 10, columns=("#1", "#2", "#3""#"))
self.tree.grid(row = 87, column = 0, columnspan = 2, padx = 20, pady = 10)
self.tree.heading("#0", text="Nombre", anchor = CENTER)
self.tree.heading("#1", text="Precio", anchor = CENTER)
self.tree.heading("#2", text="Stock", anchor = CENTER)
self.tree.heading("#3", text="Seccion", anchor = CENTER)
# SCROLL VERTICAL TREEVIEW
scrolvert = Scrollbar(frame2, command = self.tree.yview)
scrolvert.grid(row=8row=7, column=2, sticky="nsew")
self.tree.config(yscrollcommand=scrolvert.set)
# SCROLL HORIZONTAL TREEVIEW
scrolhoriz = Scrollbar(frame2, command = self.tree.xview, orient='horizontal')
scrolhoriz.grid(row=12, column=0, columnspan=2, sticky="news")
self.tree.config(xscrollcommand=scrolhoriz.set)
# BOTONES
ttk.Button(text='EDIT', command=self.edit_product).grid(row = 13, column = 0, columnspan=2, ipadx = 50, pady = 10)
ttk.Button(text='DELETE', command=self.del_product).grid(row = 13, column = 1, columnspan=2, ipadx = 50, pady = 10)
self.get_products()
# 7 - CREACION INTERFAZ GRAFICA
def interfaz_inicial(self):
global frame
# FUNCION PARA TRANSFORMAR A MAYUSCULA
# FRAME CONTENEDOR
frame = LabelFrame(self.win, text=' REGISTRAR UN NUEVO PRODUCTO: ')
frame.grid(row = 0, column = 0, columnspan = 3, pady = 15, ipadx = 5, ipady = 5)
# INPUT NAME
Label(frame, text=' Nombre: ').grid(row = 1, column = 0, padx = 20, pady = 5, sticky = W)
#self.name = Entry(frame, width=45)
self.name = UpperEntry(frame, width=45)
self.name.grid(row = 1, column = 1, sticky = W)
self.name.focus()
# INPUT PRECIO
Label(frame, text=' Precio: ').grid(row = 2, column = 0, padx = 20, pady = 5, sticky = W)
#self.price = Entry(frame, width=25)
#self.price = UpperEntry(frame, width=25)
self.price = CurrencyEntry(frame, width=25)
self.price.grid(row = 2, column = 1, sticky = W)
# INPUT STOCK
Label(frame, text=' Stock: ').grid(row = 3, column = 0, padx = 20, pady = 5, sticky = W)
#self.stock = Entry(frame, width=25)
self.stock = UpperEntry(frame, width=25)
self.stock.grid(row = 3, column = 1, sticky = W)
# INPUT SECCION
Label(frame, text=' Seccion: ').grid(row = 4, column = 0, padx = 20, pady = 5, sticky = W)
#self.section = Entry(frame, width=45)
self.section = UpperEntry(frame, width=45)
self.section.grid(row = 4, column = 1, sticky = W)
# BOTON AGREGAR PRODUCTO
ttk.Button(frame, text='AGREGAR PRODUCTO', command=self.add_product).grid(row = 5, columnspan = 2, ipadx=40, pady = 10)
# 9 - CREAR METODO PARA CONECTAR Y HACER CONSULTAS A LA BASE DE DATOS
def run_query(self, query, parameters = ()):
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
result = cursor.execute(query,parameters)
conn.commit()
return result
# 10 - OBTENER DATOS DE LA TABLA product
def get_products(self):
#limpiando treeview
records = self.tree.get_children()
for element in records:
self.tree.delete(element)
# ejeutando consulta
query = 'SELECT * FROM product ORDER BY name DESC'
db_rows = self.run_query(query)
# llenando data
for row in db_rows:
#print(row)
self.tree.insert('',0,text = row[1], values = (row[2], row[3], row[4]))
# activando focus en la tabla
child_id =11 self.tree.get_children()[-1] # for instance the last element in tuple
self.tree.focus(child_id)
self.tree.selection_set(child_id) VALIDAR CAMPOS
def validation(self):
return len(self.name.get()) != 0 and len(self.price.get()) != 0 and len(self.stock.get()) != 0 and len(self.section.get()) != 0
# 12 - AGREGAR PRODUCTOS
def add_product(self):
if self.validation():
query = 'INSERT INTO product VALUES (NULL, ?, ?, ?, ?)'
parameters = (self.name.get(), self.price.get(), self.stock.get(), self.section.get())
self.run_query(query, parameters)
self.message['text'] = 'El Producto {} ha sido agregado!!'.format(self.name.get())
self.message['font'] = ('Consolas',1411)
self.message['bg'] ='#d4edda'
self.message['fg'] ='#116158'
# LIMPIAR CAMPOS
self.name.delete(0, END)
self.price.delete(0, END)
self.stock.delete(0, END)
self.section.delete(0, END)
self.name.focus()
else:
self.message['text'] = 'Todos los campos son requeridos...'
self.message['font'] = ('Consolas',1411)
self.message['bg'] ='#f7d7da'
self.message['fg'] ='#89312f'
self.name.focus()
self.get_products()
# 13 - ELIMINAR PRODUCTOS
def del_product(self):
self.message['text'] = ''
try:
self.tree.item(self.tree.selection())['text'][0]
except IndexError as e:
self.message['text'] = 'Por favor selecciona un registro'
self.message['font'] = ('Consolas',11)
self.message['bg'] ='#f7d7da'
self.message['fg'] ='#89312f'
self.name.focus()
return
self.message['text'] = ''
name = self.tree.item(self.tree.selection())['text']
query = 'DELETE FROM product WHERE name = ?'
self.run_query(query, (name,))
self.message['text'] = 'El Producto {} ha sido eliminado!!'.format(name)
self.message['font'] = ('Consolas',11)
self.message['bg'] ='#d4edda'
self.message['fg'] ='#116158'
self.name.focus()
self.get_products()
# 14 - EDITAR PRODUCTOS
def edit_product(self):
self.message['text'] = ''
nuevo = Entry()
try:
self.tree.item(self.tree.selection())['text'][0]
except IndexError as e:
self.message['text'] = 'Por favor selecciona un registro'
self.message['font'] = ('Consolas',11)
self.message['bg'] ='#f7d7da'
self.message['fg'] ='#89312f'
self.name.focus()
return
name1 = self.tree.item(self.tree.selection())['text']
Entry(frame, textvariable = StringVar(frame, value=name1)).grid(row = 1, column = 1, sticky = W)
# 2 - VERIFICARLANZAR SIAPLICACION
class ESUpperEntry(Entry):
EL ARCHIVO MAIN PARAdef CREAR__init__(self, Eparent, INICIAR*args, LA**kwargs):
VENTANA PRINCIPAL self._var = kwargs.get("textvariable") or StringVar(parent)
super().__init__(parent, *args, **kwargs)
self.configure(textvariable=self._var)
self._to_upper()
def config(self, cnf=None, **kwargs):
self.configue(cnf, **kwargs)
def configure(self, cnf=None, **kwargs):
var = kwargs.get("textvariable")
if var is not None:
var.trace_add('write', self._to_upper)
self._var = var
super().config(cnf, **kwargs)
def __setitem__(self, key, item):
if key == "textvariable":
item.trace_add('write', self._to_upper)
self._var = item
super.__setitem__(key, item)
def _to_upper(self, *args):
self._var.set(self._var.get().upper())
class CurrencyEntry(Frame):
def __init__(
self, parent, *args,
currency_symbol="€", thousand_sep=".", decimal_sep=",", **kwargs
):
super().__init__(parent, *args, **kwargs)
self.configure(
highlightbackground="#000000", highlightcolor="#000000",
highlightthickness=1, relief=FLAT
)
self._int_var = StringVar(self)
self._dec_var = StringVar(self)
vcmd_int = (self.register(self.on_validate_int), '%S')
vcmd_dec = (self.register(self.on_validate_dec), '%S')
self._thousand_sep = thousand_sep
self._decimal_sep = decimal_sep
self._int_entry = Entry(
self, textvariable=self._int_var,
validate="key", validatecommand=vcmd_int,
borderwidth=0, relief=FLAT, justify='right',
width=15, highlightthickness=0
)
self._int_entry.pack(side="left", fill="x")
self._dec_label = Label(
self, text=decimal_sep, relief=FLAT, highlightthickness=0
)
self._dec_entry = Entry(
self, textvariable=self._dec_var,
validate="key", validatecommand=vcmd_dec,
borderwidth=0, relief=FLAT, width=2,
highlightthickness=0
)
self._sym_label = Label(
self, text=currency_symbol, relief=FLAT, highlightthickness=0
)
self._sym_label.pack(side="left")
self._int_last_index = True
self._dec_first_index = False
self._int_entry.bind('<KeyRelease>', self._on_int_release)
self._dec_entry.bind('<KeyRelease>', self._on_dec_release)
def on_validate_int(self, char):
if char not in "0123456789" and char != self._decimal_sep:
return False
return True
def on_validate_dec(self, char):
if char not in "0123456789":
return False
return True
def _on_int_release(self, event):
if self._int_entry.index(INSERT) == self._int_entry.index(END):
if self._int_last_index and event.keysym == "Right":
self._last_index = False
self._dec_entry.focus_set()
else:
self._int_last_index = True
else:
self._int_last_index = False
text = self._int_var.get().replace(self._thousand_sep, "")
if self._decimal_sep in text:
int_, dec = text.split(self._decimal_sep)
self._int_var.set(int_)
self._sym_label.pack_forget()
self._dec_label.pack(side="left")
self._dec_entry.pack(side="left")
self._sym_label.pack(side="left")
self._dec_var.set(dec[:2])
self._dec_entry.focus_set()
self.set_thousand_sep()
def _on_dec_release(self, event):
key = event.keysym
if key == "Left" and self._dec_entry.index(INSERT) == 0:
if self._dec_first_index:
self._dec_first_index = False
self._int_entry.focus_set()
else:
self._dec_first_index = True
elif key == "BackSpace" and self._dec_entry.index(INSERT) == 0:
if self._dec_first_index:
self._dec_label.pack_forget()
if self._dec_var.get() and int(self._dec_var.get()):
self._int_var.set(
self._int_var.get() + self._dec_var.get()
)
self._dec_var.set("")
self._dec_entry.pack_forget()
self.set_thousand_sep()
self._int_entry.focus_set()
self._last_index = True
self._dec_first_index = True
else:
self._dec_first_index = False
def set_thousand_sep(self):
if not (text:= self._int_var.get()):
return
sep = self._thousand_sep
new_text = (f'{int(text.replace(self._thousand_sep, "")):,}'
.replace(",", self._thousand_sep)
)
self._int_var.set(new_text)
if (dif:= new_text.count(sep) - text.count(sep)) > 0:
self._int_entry.icursor(self._int_entry.index(INSERT) + dif)
def get(self):
return decimal.Decimal(
(f"{self._int_var.get().replace(self._thousand_sep, '')}"
f".{self._dec_var.get()}")
)
if __name__ == "__main__":
window = Tk()
# 3 - PASARLE LA VENTANA CREADA A LA CLASE PRODUCT COMO PARAMETRO(INSTANCIAR)
aplication = Product(window)
# 5 - EJECUTAR VENTANA
window.mainloop()