erkangur
erkangur

Reputation: 2128

Iterating variables to change its features in Python

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?

Upvotes: 0

Views: 148

Answers (3)

unutbu
unutbu

Reputation: 879601

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)

Upvotes: 1

Katriel
Katriel

Reputation: 123652

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( ... )

Upvotes: 6

Felix Kling
Felix Kling

Reputation: 816462

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.

Upvotes: 3

Related Questions