我正在尝试创建一个看起来像这样的程序:
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'
...而只是手动输入它们不会。有人对我有什么建议吗?