I’m writing a tKinter GUI and I’ve come accross a problem. Given the the main code is way to large, I’ve made a dummy example to replicate my problem.
class test(): def __init__(self,time,a): self.time = time self.a = a def something(self): self.b = float(self.time) * self.a return {'bVar':self.b} time = np.linspace(0,100,10) testObj = test(time,2.2) print(testObj.something().get('bVar'))
The error is:
----> 9 self.b = float(self.time) * self.a 10 11 return {'bVar':self.b} TypeError: only size-1 arrays can be converted to Python scalars
If I remove the float conversion of time, then it works. But in my main GUI I need to keep float(self.time). self.a in my GUI is a tKinter entry that has to be also of type float(entry[1].get())
Any thoughts on how I can remedy this?
Advertisement
Answer
The error “only length-1 arrays can be converted to Python scalars” is raised when the function expects a single value but you pass an array instead.
Problem is that you are passing an array self.time
to the float
that expects a single value instead of an array.
You got time
using np.linspace(0, 100, 10) which returns an array of evenly spaced numbers over a specified interval.
https://numpy.org/doc/stable/reference/generated/numpy.linspace.html
Updating my answer, assuming you want to multiply each value in the list with a single value.
class Test(): def __init__(self,time,a): self.time = time self.a = a def something(self): self.b = np.array(self.time, dtype=float) * self.a return {'bVar':self.b} time = np.linspace(0,100,10) testObj = Test(time,2.2) print(testObj.something().get('bVar'))
You can set dtype=float
in numpy
array to set the data type of the array to float
. And then you can use * to multiply a single value with each value in the array.