Error = tuple index out of range ... problem with postgresql and python

0

I have the following function:

def Buscar(self):
    comando="SELECT * FROM tipo_inversion where id='"+self.palabra.get()+"';"
    conectar=Base_de_datos.BaseDeDatos()
    conectar.cursor.execute(comando)
    #rows= conectar.cursor.fetchall()
    for dat in enumerate(conectar.cursor.fetchall()):
        self.listbox.insert(0, Label(self.listbox, text=dat[0]))
        self.listbox.insert(1, Label(self.listbox, text=dat[1]))
        self.listbox.insert(2, Label(self.listbox, text=dat[2]))
        self.listbox.insert(3, Label(self.listbox, text=dat[3]))

I'm using a cycle to accommodate 4 data that I have in a table in postgresql, but I really do not know if I'm fine like that, I get this error:

self.listbox.insert(1, Label(self.listbox, text=dat[2]))
IndexError: tuple index out of range

I used to have only the listbox and with fetchall, I used to call self.listbox.insert(0, *rows) the number of rows is mentioned in the first function

but I do not like how the data shows, since they look very close and I want them to have a bit of space, so try the cycle and create a label. For this, I base myself on this code:

Label(self.ventanaBusqueda, text=dat[0]).grid(row=index+1, column=0)
        Label(self.ventanaBusqueda, text=dat[1]).grid(row=index+1, column=1)
        Label(self.ventanaBusqueda, text=dat[2]).grid(row=index+1, column=2)
        Label(self.ventanaBusqueda, text=dat[3]).grid(row=index+1, column=3)

and putting it this way, I can not accommodate it where I have the listbox, that is the position.

    
asked by sergeee30 05.03.2018 в 03:58
source

1 answer

1

The problem is that dat[2] does not exist, dat is a tuple of two elements, so index 2 does not exist.

The built-in enumerate(sequence, start=0) function receives as arguments any iterable ( secuence ) and an integer ( start ), which is 0 by default. Returns an iterator that generates tuples of two elements that contain a counter (starting in start ) and the values obtained when iterating over the sequence.

Better to see it with some examples:

>>> secuencia = ["Hola", "StackOverflow", "en", "español"]

>>> for e in enumerate(secuencia):
        print(e)

(0, 'Hola')
(1, 'StackOverflow')
(2, 'en')
(3, 'español')

>>> for e in enumerate(secuencia, 10):
        print(e)

(10, 'Hola')
(11, 'StackOverflow')
(12, 'en')
(13, 'español')


>>> for indice, palabra in enumerate(secuencia):
        print("Indice: {}  Palabra: {}".format(indice, palabra))

Indice: 0  Palabra: Hola
Indice: 1  Palabra: StackOverflow
Indice: 2  Palabra: en
Indice: 3  Palabra: español

This is the cause of the error you have, to give a more specific solution it would be necessary to know how you want the data to look exactly and the structure of your table.

    
answered by 05.03.2018 / 08:48
source