Create checkboxes with loop?

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.

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #5570

    Philipp
    Participant

    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?

    #5572

    joanca
    Participant

    Probably 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()
    
    #5577

    frederik
    Keymaster

    a better way is to use setattr

    for i in range(10):
        checkboxObject = Checkbox((10, 10, 10+30*i, 22), "label %s" % i)
        setattr(self.w, "checkBox_%s" % i, checkboxObject)
    
    #5580

    Philipp
    Participant

    joanca, 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()
    
    #5582

    Philipp
    Participant

    Boing!

    My mistake was a typo: It´s CheckBox, not Checkbox … Ah, the joys of programming!

    Thanks for your help! :-)

    #5583

    frederik
    Keymaster

    sorry, its indeed CheckBox

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.