Tkinter Application for Data Management with File Handling

Tkinter Application for Data Management

This document outlines a Python application built using the Tkinter library for managing data. It includes features for file handling, data display in a Treeview widget, and search functionalities.

Importing Libraries

The application starts by importing necessary modules:

from tkinter import *
from tkinter import ttk, messagebox
from tkinter import filedialog as fl
import os.path
import pickle

Main Window Setup

A main window titled “Datos” is created with a size of 1000×435 pixels:

ventana = Tk()
ventana.title("Datos")
ventana.geometry("1000x435")

Treeview Widget

A Treeview widget is initialized to display data in a tabular format with seven columns:

tree = ttk.Treeview(ventana, height=17)
tree["columns"] = ("column2", "column3", "column4", "column5", "column6", "column7")
tree.column("#0", width=100, minwidth=10)
tree.column("column2", width=100, minwidth=30)
tree.column("column3", width=100, minwidth=30)
tree.column("column4", width=100, minwidth=30)
tree.column("column5", width=150, minwidth=30)
tree.column("column6", width=100, minwidth=30)
tree.column("column7", width=100, minwidth=30)
tree.heading("#0", text="Correlativo", anchor="center")
tree.heading("column2", text="Codigo", anchor="center")
tree.heading("column3", text="Nombre", anchor="center")
tree.heading("column4", text="Apellido", anchor="center")
tree.heading("column5", text="Numero de telefono", anchor="center")
tree.heading("column6", text="Año de creacion", anchor="center")
tree.heading("column7", text="Zona", anchor="center")
tree.place(x=20, y=50)

Entry Widgets and Labels

Entry widgets for search and file path, along with a label, are created:

busqueda = Entry(ventana, width=50)
busqueda.place(x=20, y=20)
ruta = Entry(ventana, width=50)
ruta.place(x=450, y=20)
ruta1 = Label(text="Ruta de archivo")
ruta1.place(x=800, y=20)

File Handling Functions

Open File Function

The abr function opens a file dialog to select a file, reads its content using pickle, and populates the Treeview:

def abr():
    ru = fl.askopenfilename()
    ruta.delete(0, 'end')
    ruta.insert('insert', ru)

    tree.delete(*tree.get_children())
    with open(ru, 'rb') as arch:
        max = os.path.getsize(ru)
        pos = 0
        while pos < max:
            reg = pickle.load(arch)
            tree.insert("", 'end', values=[(reg[0]), (reg[1]), (reg[2]), (reg[3]), (reg[4]), (reg[5])])
            pos = arch.tell()

Save/Create File Function

The gdr function creates a new window to input data, saves it to a file using pickle, and handles file creation if no path is specified:

def gdr():
    g = Toplevel(ventana)
    g.geometry("400x400")
    g.title("Guardar/Crear")

    # ... (Entry widgets and labels for data input) ...

    if ruta.get() == "":
        ru = fl.asksaveasfilename()
        ruta.insert('insert', ru)

    def guarda():
        ar = ruta.get()
        c = int(cod.get())
        n = nom.get()
        a = ap.get()
        ntt = int(nt.get())
        acc = int(ac.get())
        z = zona.get()

        lista = [c, n, a, ntt, acc, z]

        with open(ar, 'ab') as arch:
            pickle.dump(lista, arch)

    guar = Button(g, text="Guardar", command=guarda)
    guar.place(x=175, y=270)

Delete Record Function

The elr function deletes the selected record from the Treeview and updates the file:

def elr():
    ar = ruta.get()
    pos = tree.selection(["values"])
    tree.delete(pos)

    arch = open(ar, 'wb')
    for fila in tree.get_children():
        x = tree.item(fila)
        list = [*x.values()]
        pickle.dump(list[6], arch)
    arch.close()

Search Functions

Functions to search by code, name, last name, phone number, year, and zone are defined. Each function filters the Treeview based on the search query:

  • bcod: Searches by code.
  • bnom: Searches by name.
  • bape: Searches by last name.
  • bnum: Searches by the last two digits of the phone number.
  • baño: Searches by year within the range of 2000-2005.
  • bzona: Searches by zone.
# Example for bcod (search by code)
def bcod():
    query = busqueda.get()
    seleccion = []
    for posicion in tree.get_children():
        if query in str(tree.item(posicion)["values"][0]):
            seleccion.append(posicion)
    tree.selection_set(seleccion)

# ... (Similar functions for bnom, bape, bnum, baño, bzona) ...

Buttons

Buttons for opening a file, creating/saving a file, deleting a record, and performing searches are created and placed on the main window:

btn1 = Button(ventana, text="Abrir archivo", command=abr)
btn1.place(x=790, y=60)
btn2 = Button(ventana, text="Crear nuevo o guardar", command=gdr)
btn2.place(x=790, y=90)
btn3 = Button(ventana, text="Eliminar", command=elr)
btn3.place(x=870, y=60)
btn4 = Button(ventana, text="Buscar codigo", command=bcod)
btn4.place(x=790, y=200)
btn5 = Button(ventana, text="Buscar nombre", command=bnom)
btn5.place(x=880, y=200)
btn6 = Button(ventana, text="Buscar apellido", command=bape)
btn6.place(x=790, y=230)
btn7 = Button(ventana, text="Buscar numero", command=bnum)
btn7.place(x=880, y=230)
btn8 = Button(ventana, text="Buscar año", command=baño)
btn8.place(x=880, y=260)
btn9 = Button(ventana, text="Buscar zona", command=bzona)
btn9.place(x=790, y=260)

Main Loop

Finally, the main event loop is started:

ventana.mainloop()

Conclusion

This Tkinter application provides basic data management capabilities with file handling and search functionalities. It demonstrates the use of Treeview, Entry widgets, Buttons, and file I/O operations using the pickle module.