开发者

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)

Ho开发者_Python百科w can I do that?


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


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.


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜