¡Claro! A continuación te presento un ejemplo básico de un sistema de registro de inventario utilizando Python, SQLite (base de datos SQL ligera integrada) y Tkinter para la interfaz gráfica. El sistema permitirá agregar, ver y eliminar productos del inventario.
Características básicas del sistema:
- Interfaz gráfica con Tkinter.
- Base de datos SQLite para almacenar los productos.
- Funcionalidades:
- Registrar un nuevo producto (nombre, cantidad y precio).
- Mostrar productos existentes.
- Eliminar productos.
Código completo:
import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
class InventoryApp:
def __init__(self, root):
self.root = root
self.root.title("Sistema de Inventario")
self.root.geometry("600x400")
# Conexión a la base de datos y creación de tabla si no existe
self.conn = sqlite3.connect("inventario.db")
self.cursor = self.conn.cursor()
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS productos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nombre TEXT NOT NULL,
cantidad INTEGER NOT NULL,
precio REAL NOT NULL
)
""")
self.conn.commit()
# Widgets - etiquetas, entradas y botones
tk.Label(root, text="Nombre:").place(x=20, y=20)
self.entry_nombre = tk.Entry(root)
self.entry_nombre.place(x=100, y=20)
tk.Label(root, text="Cantidad:").place(x=20, y=60)
self.entry_cantidad = tk.Entry(root)
self.entry_cantidad.place(x=100, y=60)
tk.Label(root, text="Precio:").place(x=20, y=100)
self.entry_precio = tk.Entry(root)
self.entry_precio.place(x=100, y=100)
self.btn_agregar = tk.Button(root, text="Agregar Producto", command=self.agregar_producto)
self.btn_agregar.place(x=100, y=140)
self.btn_eliminar = tk.Button(root, text="Eliminar Producto", command=self.eliminar_producto)
self.btn_eliminar.place(x=250, y=140)
# Tabla para mostrar productos
self.tree = ttk.Treeview(root, columns=("ID", "Nombre", "Cantidad", "Precio"), show="headings")
self.tree.heading("ID", text="ID")
self.tree.column("ID", width=30)
self.tree.heading("Nombre", text="Nombre")
self.tree.heading("Cantidad", text="Cantidad")
self.tree.column("Cantidad", width=80)
self.tree.heading("Precio", text="Precio")
self.tree.column("Precio", width=80)
self.tree.place(x=20, y=190, width=560, height=180)
self.cargar_datos()
def agregar_producto(self):
nombre = self.entry_nombre.get()
cantidad = self.entry_cantidad.get()
precio = self.entry_precio.get()
if not nombre or not cantidad or not precio:
messagebox.showwarning("Aviso", "Por favor llene todos los campos.")
return
try:
cantidad = int(cantidad)
precio = float(precio)
except ValueError:
messagebox.showerror("Error", "Cantidad debe ser entero y precio decimal.")
return
self.cursor.execute("INSERT INTO productos (nombre, cantidad, precio) VALUES (?, ?, ?)",
(nombre, cantidad, precio))
self.conn.commit()
self.limpiar_campos()
self.cargar_datos()
def cargar_datos(self):
for registro in self.tree.get_children():
self.tree.delete(registro)
self.cursor.execute("SELECT * FROM productos")
for fila in self.cursor.fetchall():
self.tree.insert("", "end", values=fila)
def eliminar_producto(self):
seleccionado = self.tree.focus()
if not seleccionado:
messagebox.showwarning("Aviso", "Seleccione un producto para eliminar.")
return
valores = self.tree.item(seleccionado, 'values')
id_producto = valores[0]
confirmar = messagebox.askyesno("Confirmar", f"¿Eliminar el producto '{valores[1]}'?")
if confirmar:
self.cursor.execute("DELETE FROM productos WHERE id=?", (id_producto,))
self.conn.commit()
self.cargar_datos()
def limpiar_campos(self):
self.entry_nombre.delete(0, tk.END)
self.entry_cantidad.delete(0, tk.END)
self.entry_precio.delete(0, tk.END)
if __name__ == "__main__":
root = tk.Tk()
app = InventoryApp(root)
root.mainloop()
Cómo usar
- Guarda este código en un archivo llamado
inventario.py.
- Ejecuta con Python 3:
python inventario.py
- La ventana te permite ingresar nombre, cantidad y precio y agregar un producto.
- Se muestran los productos en la tabla.
- Puedes seleccionar un producto y eliminarlo con el botón "Eliminar Producto".
Mejoras posibles
- Validar mejor los datos.
- Permitir edición de productos.
- Buscar productos.
- Mejor diseño visual con más widgets y estilos.
- Crear archivo ejecutable
.exe con PyInstaller para que sea una aplicación instalable.
Si quieres, puedo ayudarte también con estas mejoras o con la creación del ejecutable. ¿Te gustaría?