0

Possible Duplicate:
Changing variable names with Python for loops

I have created a form that has 24 line edit boxes (objects) in it. I want to update an attribute on each object based upon data entered by the user (I want to enable or disable the line edit box).

So I am trying to do something like:

    if self.cmbSelectDevice.currentText() == 'Adtran 904' :
        for EnableLine in range(1,  5) :
            self.lblFxsLine'EnableLine'.setEnabled(1)
        for DisableLine in range (6, 24) :
            self.lblFxsLine'DisableLine'.setEnabled(0)

'EnableLine' and 'DisableLine' are the values I am trying to substitute. If I did this all manually it woudl look something like:

    if self.cmbSelectDevice.currentText() == 'Adtran 904' :
        self.lblFxsLine1.setEnabled(1)
        self.lblFxsLine2.setEnabled(1)
        self.lblFxsLine3.setEnabled(1)
        etc...
        self.lblFxsLine6.setEnabled(0)
        self.lblFxsLine7.setEnabled(0)
        etc...

List and dictionaries don't really work here since I am trying to manipulate attributes on objects in a form (at least I think they don't, I am really new to python).

Any help/suggestions greatly appreciated.

Thanks!

Community
  • 1
  • 1

2 Answers2

1

There's nothin preventing you from putting your lblFxsLine into a dictionary or list.

self.lblFxsLines = [lblFxsLine for i in range(1,25)]

...

if self.cmbSelectDevice.currentText() == 'Adtran 904' :
    for enableLine in range(1,  5) :
        self.lblFxsLines[enableLine].setEnabled(1)
    for disableLine in range (6, 24) :
        self.lblFxsLines[disableLine].setEnabled(0)
Don Question
  • 11,227
  • 5
  • 36
  • 54
0

I’m not familiar with the framework you’re using, but if you want to access an attribute with a procedurally generated name, you’ll likely want to use getattr.

Your example would then become:

for enable_line in range(1, 6):  # Note: upper bound is exclusive
    getattr(self, 'lblFxsLine%d' % enable_line).setEnabled(1)
for disable_line in range(6, 25):
    getattr(self, 'lblFxsLine%d' % disable_line).setEnabled(0)

I would be very surprised, though, if your framework didn’t offer you some way to get a list of these edit boxes.

dhwthompson
  • 2,501
  • 1
  • 15
  • 11