J.Swersey
J.Swersey

Reputation: 171

Creating multiple variables / strings within loops in Python

I'm trying to create a program that, well, looks something like this:

          self.b1 = Checkbutton(self, variable=self.b1v, text="1.")
          self.b1.grid()
          self.b2v = IntVar()
          self.b2 = Checkbutton(self, variable=self.b2v, text="2.")
          self.b2.grid()
          self.b3v = IntVar()
          self.b3 = Checkbutton(self, variable=self.b3v, text="3.")
          self.b3.grid()
          self.b4v = IntVar()

Well, kinda like that, just... 30+ times. There has GOT to be a better way to do this. However, I have no idea how to do this in a loop. I imagine it would look something like this:

          while i <= 32:
                 n = "self.b" + str(i) + "v = IntVar() \n"
                 n += "self.b" + str(i) + " = Checkbutton(self, variable=self.b" + str(i) + "v) \n"
                 n += "self.b" + str(i) + ".grid()\n"
                 exec(n)

...Or something like that... But that throws an error:

    Traceback (most recent call last):
  File "/Users/jonahswersey/Documents/toggle flags.py", line 126, in <module>
    app = Application()
  File "/Users/jonahswersey/Documents/toggle flags.py", line 93, in __init__
    self.createWidgets()
  File "/Users/jonahswersey/Documents/toggle flags.py", line 117, in createWidgets
    exec(m)
  File "<string>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 2337, in __init__
    Widget.__init__(self, master, 'checkbutton', cnf, kw)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1923, in __init__
    BaseWidget._setup(self, master, cnf)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1903, in _setup
    if cnf.has_key('name'):
AttributeError: IntVar instance has no attribute 'has_key'

...whereas just manually entering them doesn't. Anyone have any advice for me?

Upvotes: 2

Views: 1012

Answers (2)

Joel Cornett
Joel Cornett

Reputation: 24788

Something like this?

num_buttons = 3
self.b_vars = [IntVar() for i in range(num_buttons)]
self.b = [CheckButton(self, variable=self.b_vars[i], text="%d." % (i + 1)) for i in range(num_buttons)]
for button in self.b:
    button.grid()

Upvotes: 7

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

You're looking for setattr().

Upvotes: 3

Related Questions