Nurzhan Nogerbek Nurzhan Nogerbek - 6 months ago 19
Python Question

Show array in listbox

Can anyone tell me what I did wrong?! I made a GUI with tkinter in Python 3. I am tring to create array and show it to listbox when the window opens. Below, you can see code that I used.

ERROR:

Population.X[i] = float(random.random()) * self.XMin
IndexError: list assignment index out of range


CODE:

class Population:
X = []
Y = []

class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.widgets()
self.create_array()

def widgets(self):
self.first_listbox = Listbox(self)
self.first_listbox.grid()

def create_array(self):
i = 0
while i < 20:
Population.X[i] = float(random.random()) * self.XMin
# x = random.random() - Random float x | 0.0 <= x < 1.0 |
if Population.X[i] == 0:
Population.X[i] = -0.1
Population.Y[i] = 1 / Population.X[i]
i += 1
while i < 20:
self.first_listbox.insert(i, Population.X[i])
i += 1

root = Tk()
root.geometry("600x400")
app = Application(root)
root.mainloop()

Answer

Appending to a list

You get an IndexError because you're trying to access element number 0 while your list has no element.

You can't create a new index like this:

my_list = []
my_list[12] = 'whatever'

But you can append to the list iteratively:

def create_array(self):

    for i in range(20):

        new_item = float(random.random()) * self.XMin)

        if new_item == 0:
            new_item = -0.1

        Population.X.append(new_item)
        Population.Y.append(1 / new_item)

Filling the listbox

Also, this part of your code would never be reached:

    while i < 20:
        self.first_listbox.insert(i, Population.X[i])
        i += 1

because i is 20 when getting out of the former loop. You'd need to set i back to 0 or better to rethink the whole thing:

for item in Population.X:
    self.first_listbox.insert(END, item)

Minor style remark

Note that

        new_item = float(random.random()) * self.XMin)

        if new_item == 0:
            new_item = -0.1

could be written in one line:

        new_item = float(random.random()) * self.XMin) or -0.1

but the former is totally fine and easier to grasp. It is mostly a matter of taste.

Comments