How to pass values from a listbox in Tkinter to an array and then add the values together?

Viewed 187

Let me state that I am new to using this language. but I'm progressing thanks to many readings made online. I'm creating a little program to make work in the office easier.

The problem that I can't solve now is the following: from a database, through a search, I can pull out of the numerical data that I see in a listbox. I would like to put these data presented in the listbox in an array and then with the Python native function "SUM" get the result. This is my intent.

But I can't. Here is the code:

def Calcola_Isi_dovuto():
    lista = list(dovutolist.get(0,END))
    print(lista)
    dovuto = arr.array('d',lista)
    print(dovuto)
    somma = sum(dovuto)
    print(somma)

And errors:

usr/bin/python3.6 /media/diakrufus/Maxtor/xxxxxx/xx.py
[('1322.20',), ('1322.80',)]
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/media/diakrufus/Maxtor/xxxxxxxxxxxx/xxxxx.py", line 1185, in 
Calcola_Isi_dovuto
dovuto = arr.array('d',lista)
TypeError: must be real number, not tuple
1 Answers

As you can see from the output of print(lista), you have got a list of tuples as the output ([('1322.20',), ('1322.80',)]).

It is expected, from the output, to pass a list of numbers, so to sum them you may use a workaround, like:

dovuto = arr.array('d',[float(l[0]) for l in lista])

The last part is list comprehension where we made the list to be [1322.20, 1322.80] (l[0] here means the first element of every subelement).

Related