RoboFont › Forums › Help / General › Create checkboxes with loop?
This topic contains 5 replies, has 3 voices, and was last updated by frederik 7 years, 4 months ago.
-
AuthorPosts
-
June 12, 2013 at 12:37 #5570
Hi,
this may be a basic Python-class question.
I´m trying to show a basic window with multiple checkboxes in it. Which works fine, when I add them manually with their own attribute (?). (Example: https://gist.github.com/axani/5764824 )
But when I try to create multiple checkboxes with a loop I get an Assertion Error, because “self.w.checkbox = …” is used repeatedly.
AssertionError: can't replace vanilla attribute
So how can I build “self.w.checkbox1 =…”, “self.w.checkbox2 = …”, etc. via a loop?
June 12, 2013 at 13:40 #5572Probably there’s a better way of doing this, but at least, in the meantime, this works:
) sorry I don’t know how to format code properly in the forum :(from vanilla import * class checkboxWindow: def __init__(self): self.w = Window((400,400), 'SetOrganizer') for n in range(5): exec("self.w.checkBox%s = CheckBox((10, 10 + (25*n+1), -10, -10), 'Label', callback=self.checkBoxCallback, value=True)" % (n)) self.w.open() def checkBoxCallback(self, sender): print sender.get(), sender.getTitle() checkboxWindow()June 12, 2013 at 14:40 #5577a better way is to use
setattrfor i in range(10): checkboxObject = Checkbox((10, 10, 10+30*i, 22), "label %s" % i) setattr(self.w, "checkBox_%s" % i, checkboxObject)June 12, 2013 at 15:18 #5580joanca, frederik, thanks for your fast answers!
joancas suggestion works. Though I read often that
exec()
might be dangerous to use. Unfortunately I get an NameError with frederiks variant:
NameError: global name 'Checkbox' is not defined
This is my current code:
from vanilla import * class setOrganizer(): def __init__(self): self.w = Window((400,400), 'checkBoxWindow') for i in range(10): checkboxObject = Checkbox((10, 10, 10+30*i, 22), "label %s" % i) setattr(self.w, "checkBox_%s" % i, checkboxObject) self.w.open() setOrganizer()June 12, 2013 at 17:04 #5582Boing!
My mistake was a typo: It´s CheckBox, not Checkbox … Ah, the joys of programming!
Thanks for your help! :-)
June 12, 2013 at 21:04 #5583sorry, its indeed
CheckBox -
AuthorPosts
You must be logged in to reply to this topic.