Modify data from a listbox in python with tkinter using postgresql ... mouseEvent

0

I have an interface where I show a list of data from different clients with a Listbox. I was wondering if it is possible to select a data from there and that can be modified directly?

those are the data that I have in postgresql

and here for example, I select the phone option and that this option appears in the Entry to only modify and that in postgresql an update is made. I used to program in java before and I remember doing this:

JButton btnModificar = new JButton("Actualizar");
    btnModificar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String [] registro= {textTitulo.getText(),textProductora.getText(),textArtista.getText(),textPrecio.getText(), textCodigo.getText()};
            int opcion= actualizarRegistros(registro);
            if(opcion != 0){
                JOptionPane.showMessageDialog(null, "Registro Actualizado");
                FormularioDiscos volver=new FormularioDiscos();
                volver.setVisible(true);
                Discos.this.dispose();
            }
        }
    });

and the updateRegistration () function:

public static int actualizarRegistros(String [] dato){
    int result = 0;
    String sql = "UPDATE \"Disco\" SET "
            + "\"Titulo\"='"+dato[0]+"', \"Productora\"='"+dato[1]+"', "
            + "\"Artista\"='"+dato[2]+"', "
            + "\"Precio\"='"+dato[3]+"',\"Codigo\"='"+dato[4]+"'WHERE \"Codigo\" = '"+dato[4]+"'";
    conectar();
    try {
        sentencia = conexion.createStatement();
        result=sentencia.executeUpdate(sql);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return result;

but I do not know what to do in the case of an actionListener or actionPerformed in python, is this possible? Is it allowed from a listbox? I understand that there is a module called pymouse, but I could not install it, I had problems ... would this module help me?

this is the Client module, the one I want to modify:

from tkinter import *
import psycopg2
import sys
import pprint
import Base_de_datos
#import Base_de_datos 
#import MergeSort

class Cliente:
    def __init__(self,codigoTarjeta=None,nombre=None,telefono=None,direccion=None,edad=None):
        self.codigoTarjeta=codigoTarjeta
        self.nombre=nombre
        self.telefono=telefono
        self.direccion=direccion
        self.edad=edad

    def ingresar(self):
        self.ventanaIngresar= Toplevel()
        self.ventanaIngresar.geometry("570x400")
        self.ventanaIngresar.title("Cliente")
        img = PhotoImage(file="C:/Users/checo/Desktop/Casino3.png")
        imagen= Label(self.ventanaIngresar,image=img)
        imagen.pack()
        Label(self.ventanaIngresar, text="Cliente",background="LavenderBlush",font=("Cambria",14)).place(x=5,y=0)
        Label(self.ventanaIngresar, text="Codigo de tarjeta: ",background="LavenderBlush",font=("Cambria",11)).place(x=0,y=30)
        Label(self.ventanaIngresar, text="Nombre: ",background="LavenderBlush",font=("Cambria",11)).place(x=0,y=60)
        Label(self.ventanaIngresar, text="Telefono: ",background="LavenderBlush",font=("Cambria",11)).place(x=0,y=90)
        Label(self.ventanaIngresar, text="Direccion: ",background="LavenderBlush",font=("Cambria",11)).place(x=0,y=120)
        Label(self.ventanaIngresar, text="Edad: ",background="LavenderBlush",font=("Cambria",11)).place(x=0,y=150)

        self.codigoTarjeta=StringVar()
        Entry(self.ventanaIngresar, textvariable=self.codigoTarjeta).place(x=120,y=30)
        self.nombre=StringVar()
        Entry(self.ventanaIngresar, textvariable=self.nombre).place(x=65,y=60)
        self.telefono=StringVar()
        Entry(self.ventanaIngresar, textvariable=self.telefono).place(x=70,y=90)
        self.direccion=StringVar()
        Entry(self.ventanaIngresar, textvariable=self.direccion).place(x=75,y=120)
        self.edad=StringVar()
        Entry(self.ventanaIngresar, textvariable=self.edad).place(x=50,y=150)

        Button(self.ventanaIngresar,text="Guardar",background="FireBrick",font=("Cambria",11),
                   width=15,command=self.BD).place(x=420,y=5)

        Button(self.ventanaIngresar,text="Modificar",background="FireBrick",font=("Cambria",11),
                   width=15).place(x=420,y=365)

        Button(self.ventanaIngresar,text="Mostrar",background="FireBrick",font=("Cambria",11),
                     width=15,command=self.Mostrar).place(x=0,y=365)

        Button(self.ventanaIngresar,text="Eliminar",background="FireBrick",font=("Cambria",11),
                     width=15,command=self.Eliminar).place(x=220,y=365)

        self.ventanaIngresar.mainloop()
    def BD(self):
        conectar=Base_de_datos.BaseDeDatos()
        comando="INSERT INTO public.Cliente("'"codigoTarjeta"'", nombre, telefono, direccion, edad) VALUES('"+self.codigoTarjeta.get()+"','"+self.nombre.get()+"','"+self.telefono.get()+"','"+self.direccion.get()+"','"+self.edad.get()+"')"
        comando2="INSERT INTO public.Recarga("'"idCliente"'",saldo2) VALUES('"+self.codigoTarjeta.get()+"', 0 )"
        print(comando)
        conectar.cursor.execute(comando)
        conectar.cursor.execute(comando2)
    def Mostrar(self):
        comando="SELECT * FROM cliente;"
        conectar=Base_de_datos.BaseDeDatos()
        conectar.cursor.execute(comando)
        Scroll=Scrollbar(self.ventanaIngresar, orient=VERTICAL)
        self.listbox=Listbox(self.ventanaIngresar, font=("Cambria",9), background="LavenderBlush", borderwidth=0, yscrollcommand=Scroll.set,height=12,relief="sunken",width=78)
        self.listbox.place(x=5, y=180)
        Scroll.config(command=self.listbox.yview)
        Scroll.pack(side=RIGHT, fill=Y)
        for dato1, dato2 in enumerate(conectar.cursor.fetchall()):
            self.listbox.insert(0, "Codigo de Tarjeta: {}".format(dato2[0]))
            self.listbox.insert(1, "Nombre: {}".format(dato2[1]))
            self.listbox.insert(2, "Telefono: {}".format(dato2[2]))
            self.listbox.insert(3, "Direccion: {}".format(dato2[3]))
            self.listbox.insert(4, "Edad: {}".format(dato2[4]))
            self.listbox.insert(5, " ")
    def Eliminar(self):
        self.palabra=None
        self.ventanaEliminar=Toplevel()
        self.ventanaEliminar.geometry("265x298")
        self.ventanaEliminar.title("Eliminar")
        Label(self.ventanaEliminar, text="Codigo del cliente",font=("Calibri Light",14)).place(x=5,y=0)
        self.palabra=StringVar()
        Entry(self.ventanaEliminar, textvariable=self.palabra).place(x=70,y=30)
        Button(self.ventanaEliminar,text="Buscar",font=("Cambria",11),
                   width=10,command=self.Buscar).place(x=85,y=60)
    def Buscar(self):          
        comando="SELECT * FROM cliente where "'"codigoTarjeta"'"='"+self.palabra.get()+"';"
        conectar=Base_de_datos.BaseDeDatos()
        conectar.cursor.execute(comando) 
        self.listbox=Listbox(self.ventanaEliminar, font=("Cambria",9), background="LavenderBlush", borderwidth=0,height=10,relief="sunken",width=35)
        self.listbox.place(x=5, y=90)
        for dato1, dato2 in enumerate(conectar.cursor.fetchall()):
            self.listbox.insert(0, "Codigo de Tarjeta: {}".format(dato2[0]))
            self.listbox.insert(1, "Nombre: {}".format(dato2[1]))
            self.listbox.insert(2, "Telefono: {}".format(dato2[2]))
            self.listbox.insert(3, "Direccion: {}".format(dato2[3]))
            self.listbox.insert(4, "Edad: {}".format(dato2[4]))
            self.listbox.insert(5, " ")
        Button(self.ventanaEliminar,text="Eliminar",font=("Cambria",11),
                width=10, command=self.Eliminacion).place(x=85,y=240)
    def Eliminacion(self):
        self.ventanaEliminar.destroy()
        comando="DELETE FROM cliente where "'"codigoTarjeta"'"='"+self.palabra.get()+"';"
        conectar=Base_de_datos.BaseDeDatos()
        conectar.cursor.execute(comando)
        self.ventanaMensaje=Toplevel()
        self.ventanaMensaje.geometry("210x80")
        self.ventanaMensaje.title("Eliminar")
        Label(self.ventanaMensaje, text="LISTO!! Registro eliminado",font=("Calibri Light",14)).place(x=5,y=10)
    
asked by Gonzo30 08.05.2018 в 22:27
source

1 answer

0

As I put you in the comment, you have to intercept the event <<ListboxSelect>> . The code you have put is too long. You should have set a minimum and reproducible example, as recommended in the forum rules.

I'll give you a short example of how it would be done:

from tkinter import *
from tkinter import ttk

class ListWidget(Frame):

    def __init__(self, root, valores):

        self.valores = valores

        super().__init__(root)

        lstvar = StringVar(self, value=valores)
        self.lst = Listbox(self, listvariable=lstvar)
        self.lst.bind("<<ListboxSelect>>", self.seleccion)
        self.lst.grid(column=0, row=0, sticky=(N, W, E, S))

        s = ttk.Scrollbar(self, orient=VERTICAL, command=self.lst.yview)
        self.lst["yscrollcommand"] = s.set
        s.grid(column=1, row=0, sticky=(N, S))

        self.entryVar = StringVar(self, value='Pulsa un valor')
        self.entry = ttk.Entry(self, textvariable=self.entryVar)
        self.entry.grid(column=0, row=1, sticky=(W, E))

    def seleccion(self, *args):
        idxs = self.lst.curselection()
        if len(idxs) == 1:
            idx = int(idxs[0])
            self.lst.see(idx)
            self.entryVar.set(self.valores[idx])


if __name__ == "__main__":

    # ejemplo de datos
    DATOS = sum(([f"nombre{i}",f"telefono{i}"] for i in range(100)),[])

    root = Tk()
    lst = ListWidget(root, DATOS)
    lst.pack()
    root.mainloop()
    
answered by 14.05.2018 / 21:59
source