views:

63

answers:

3

I assigned values with setattr() function in a loop:

for i in range(30):
        for j in range(6):  
            setattr(self, "e"+str(i)+str(j), Entry(self.top))

, then I want to apply .grid() func. to all these variables with a loop.

For example,

self.e00.grid(row= 0, column= 0)

How can I do that?

+3  A: 

Use getattr():

getattr(self, "e00").grid(row=0, column=0)

or correspondingly in a loop:

getattr(self, "e"+str(i)+str(j)).grid(row=0, column=0)

Though there might be a better solution, depending on what your code is actually doing.

Felix Kling
+6  A: 

This is not the right way to go about things. Make one attribute and put all the data in it.

import numpy as np
self.matrix = np.array( ( 6, 30 ), Entry( self.top ) )

for row in self.matrix:
    for elt in row:
        elt.grid( ... )
katrielalex
Why this is better?
erkangur
Because you can have one variable instead of 30*6 and you can manipulate the elements without the ugly and slow string manipulation + getattr/setattr. Plus, because it's the right tool for the job and already there - no point in re-inventing the wheel.
delnan
numpy.array gives error: matrix = numpy.array( (6,10), Entry(root)) TypeError: data type not understood
erkangur
Apologies; you need to define a custom `dtype` if you want to use `Entry` in a numpy array: http://stackoverflow.com/questions/2350072/custom-data-types-in-numpy-arrays. If you can't be bothered, use ~unutbu's suggestion for a list of lists -- it will be slower, but at this size it doesn't really matter.
katrielalex
+1  A: 

Perhaps use a list of lists for your matrix instead:

self.ematrix = [ [ Entry(self.top) for j in range(6)]  # columns
                                   for i in range(30)] # rows

for i,row in enumerate(self.ematrix):
    for j,elt in enumerate(row):
        elt.grid(row=i,column=j)
unutbu