I made a program which has a table that shows the id and the amount, with 2 buttons, delete and update.
I wrote one try-except
for when no value is selected, a message appears saying that you have to select an amount. When I do it with the delete button, I get directly that the amount was deleted, as if I didn't notice this error and continued with the code. And when I press update I get this error:
IndexError: string index out of range
I just get this line:
old_price = self.tree.item(self.tree.selection())['values'][0]
Here I leave the code:
def delete_product(self):
self.mesagge['text'] = ''
try:
self.tree.item(self.tree.selection())['text']
except IndexError as e:
self.mesagge['text'] = 'Selecciona un importe'
return
self.mesagge['text'] = ''
name = self.tree.item(self.tree.selection())['text']
query = 'DELETE FROM importes WHERE id = ?'
self.run_query(query, (name, ))
self.mesagge['text'] = 'El importe fue eliminado'
self.get_products()
def edit_product(self):
self.mesagge['text'] = ''
try:
self.tree.item(self.tree.selection())['text']
except IndexError as e:
self.mesagge['text'] = 'Selecciona un importe'
return
old_price = self.tree.item(self.tree.selection())['values'][0]
self.edit_wind = Toplevel()
self.edit_wind.title("Editar importe")
# Old Price
Label(self.edit_wind, text = 'Importe actual').grid(row=0, column=1)
Entry(self.edit_wind, textvariable= StringVar(self.edit_wind, value = old_price), state='readonly').grid(row=0, column=2)
# New Price
Label(self.edit_wind, text='Nuevo importe').grid(row=1, column=1)
new_price = Entry(self.edit_wind)
new_price.grid(row=1, column=2)
# Button
Button(self.edit_wind, text='Actualizar', command = lambda: self.edit_records(new_price.get(), old_price)).grid(row=2, column=2, sticky=W+E)
def edit_records(self, new_price, old_price):
query = 'UPDATE importes SET importe = ? WHERE importe = ?'
parameters = (new_price, old_price)
self.run_query(query, parameters)
self.edit_wind.destroy()
self.mesagge['text'] = "El importe fue actualizado"
self.get_products()
The problem is that no
IndexError
. The methodttk.TreeView.item
generates a dictionary of the form:when no rows are selected. This makes
name
it an empty string (key value"text"
), there is no indexing error because you don't index.In the second case as "values" is an empty string and the try passed, when doing
what you're actually trying to do is index on an empty string:
with the logical
IndexError
, this time yes, but it is not captured by anytry-except
.Don't use a
try-except
, take advantage of the fact that itself.tree.selection
returns an empty tuple if there are no selected rows :