sábado, 26 de junio de 2021

Añade nueva funcionalidad a la agenda con Python

 Añadimos nueva funcion a la agenda para buscar un contacto por su identificador.


El codigo completo es el siguiente:
Script principal::
from tkinter import *
from tkinter import messagebox
from baseDatos import *
ANCHO = 560
ALTO = 540
POSX = 300
POSY = 400
anchoAlto = str(ANCHO)+"x"+str(ALTO)
posicionX = "+"+str(POSX)
posicionY = "+"+str(POSY)
colorVentana = "blue"
colorLetra = "white"


def mostrarMensaje(titulomensaje):
    messagebox.showinfo(titulomensaje)


def limpiarDatos():
    nombre.set("")
    apellidos.set("")
    telefono.set("")
    email.set("")
    ID.set(0)
    text.delete(1.0END)


def guardar():
    crearTabla()
    if((nombre.get() == ""or (apellidos.get() == "")):
        mostrarMensaje("Error""Debes rellenar los datos")
    else:
        datos = nombre.get(), apellidos.get(), telefono.get(), email.get()
        mostrarMensaje("Guardar""Contacto guardado")
        insertar(datos)
        limpiarDatos()
        mostrar()


def actualizar():
    crearTabla()
    if((ID.get() == ""or (ID.get() == 0or (nombre.get() == "")):
        mostrarMensaje("Error""Debes rellenar los datos")
    else:
        try:
            modificar(ID.get(), nombre.get(), apellidos.get(),
                      telefono.get(), email.get())
            mostrarMensaje("Modificar""Contacto modificado")
            limpiarDatos()
            mostrar()
        except:
            mostrarMensaje("Error""Identificador no encontrado")


def eliminar():
    if((ID.get() == ""or (ID.get() == 0)):
        mostrarMensaje("Error""Debes insertar un identificador valido")
    else:
        try:
            borrar(ID.get())
            mostrarMensaje("Borrar""Contacto borrado")
            limpiarDatos()
            mostrar()
        except:
            mostrarMensaje("Error""Identificador no encontrado")


def mostrar():
    listado = consultar()
    text.delete(1.0END)
    text.insert(INSERT"ID\tNombre\tApellidos\t\tTelefono\tEmail\n")
    for elemento in listado:
        id = elemento[0]
        nombre = elemento[1]
        apellidos = elemento[2]
        telefono = elemento[3]
        email = elemento[4]
        text.insert(INSERTid)
        text.insert(INSERT"\t")
        text.insert(INSERTnombre)
        text.insert(INSERT"\t")
        text.insert(INSERTapellidos)
        text.insert(INSERT"\t\t")
        text.insert(INSERTtelefono)
        text.insert(INSERT"\t")
        text.insert(INSERTemail)
        text.insert(INSERT"\n")


def buscar():
    if((ID.get() == ""or (ID.get() == 0)):
        mostrarMensaje("Error""Debes insertar un identificador valido")
    else:
        contactos = dameContacto(ID.get())
        for contacto in contactos:
            ID.set(contacto[0])
            nombre.set(contacto[1])
            apellidos.set(contacto[2])
            telefono.set(contacto[3])
            email.set(contacto[4])
        mostrarMensaje("Buscar""Contacto encontrado")


ventana = Tk()
ventana.config(bg=colorVentana)
ventana.geometry(anchoAlto+posicionX+posicionY)
ventana.title("Agenda")
frame = Frame()
frame.config(width=ANCHOheight=ALTO)
frame.config(bg=colorVentana)
frame.pack()
# variables
ID = IntVar()
nombre = StringVar()
apellidos = StringVar()
telefono = StringVar()
email = StringVar()
# widgets
etiquetaID = Label(frametext="ID: ").place(x=50y=50)
cajaID = Entry(frametextvariable=ID).place(x=130y=50)
etiquetaNombre = Label(frametext="Nombre: ").place(x=50y=90)
cajaNombre = Entry(frametextvariable=nombre).place(x=130y=90)
etiquetaApellidos = Label(frametext="Apellidos: ").place(x=50y=130)
cajaApellidos = Entry(frametextvariable=apellidos).place(x=130y=130)
etiquetaTelefono = Label(frametext="Telefono: ").place(x=50y=170)
cajaTelefono = Entry(frametextvariable=telefono).place(x=130y=170)
etiquetaEmail = Label(frametext="Email: ").place(x=50y=210)
cajaEmail = Entry(frametextvariable=email).place(x=130y=210)
text = Text(frame)
text.place(x=50y=240width=500height=200)
botonAñadir = Button(frametext="Añadir",
                     command=guardar).place(x=150y=500)
botonBorrar = Button(frametext="Borrar",
                     command=eliminar).place(x=200y=500)
botonConsultar = Button(frametext="Consultar",
                        command=mostrar).place(x=250y=500)
botonModificar = Button(frametext="Actualizar",
                        command=actualizar).place(x=320y=500)
botonBuscar = Button(frametext="Buscar"command=buscar).place(x=390y=500)
ventana.mainloop()


Script base de datos:
import sqlite3


def conectar():
    conexion = sqlite3.connect("agenda.db")
    cursor = conexion.cursor()
    return conexioncursor


def crearTabla():
    conexioncursor = conectar()
    sql = """
        CREATE TABLE IF NOT EXISTS agenda(
            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
            nombre VARCHAR(20) NOT NULL,
            apellidos VARCHAR(20) NOT NULL,
            telefono VARCHAR(14) NOT NULL,
            email VARCHAR(20) NOT NULL
        )
    """
    if(cursor.execute(sql)):
        print("Tabla creada")
    else:
        print("No se pudo crear la tabla")
    conexion.close()


def insertar(datos):
    conexioncursor = conectar()
    sql = """
    INSERT INTO agenda(nombre,apellidos,telefono,email) VALUES (?,?,?,?)
    """
    if(cursor.execute(sqldatos)):
        print("Datos guardados")
    else:
        print("No se pudieron guardar los datos")
    conexion.commit()
    conexion.close()


def consultar():
    conexioncursor = conectar()
    sql = "SELECT id,nombre,apellidos,telefono,email from agenda"
    cursor.execute(sql)
    listado = []
    for fila in cursor:
        listado.append(fila)
        # print("ID = ", fila[0])
        # print("Nombre = ", fila[1])
        # print("Telefono = ", fila[2], "\n")
    listado.sort()
    conexion.close()
    return listado


def dameContacto(id):
    conexioncursor = conectar()
    sql = "SELECT * from agenda where id="+str(id)
    cursor.execute(sql)
    contacto = cursor.fetchall()
    conexion.close()
    return contacto


def modificar(idnombreapellidostelefonoemail):
    conexioncursor = conectar()
    sql = "UPDATE agenda SET nombre='"+nombre+"',apellidos='"+apellidos + \
        "', telefono='"+telefono+"', email='"+email+"' where ID="+str(id)
    cursor.execute(sql)
    cursor.close()
    conexion.commit()
    conexion.close()


def borrar(id):
    conexioncursor = conectar()
    sql = "DELETE from agenda where ID="+str(id)
    cursor.execute(sql)
    cursor.close()
    conexion.commit()
    conexion.close()

No hay comentarios:

Publicar un comentario

Se procedera a revision para su pronta publicacion en caso de que no incumpla las normas de blogger.