2

我正在尝试创建一个看起来像这样的程序:

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

嗯,有点像那样,只是...... 30+次。必须有更好的方法来做到这一点。但是,我不知道如何循环执行此操作。我想它看起来像这样:

          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)

...或类似的东西...但这会引发错误:

    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'

...而只是手动输入它们不会。有人对我有什么建议吗?

4

2 回答 2

7

像这样的东西?

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()
于 2012-06-01T15:25:59.447 回答
3

你正在寻找setattr().

于 2012-06-01T15:24:58.017 回答