Forum Archive

I can’t find my error ? 😤🤯

Enez Houad

I have been using Pythonista occasionally for two years now. With the help of the forum and by rummaging through the web, I manage to make some nice little applications. However, I regularly come up against basic problems related to my lack of Python skills. This is the case today ;-)
I can't understand why my script doesn't work.
I just want to make a class of Buttons... but my title doesn't display.
My mistake must be stupid, but I can't find it!

import ui

class MyButton (ui.View):

    def __init__(self, *args, **kwargs):        
        self.btn = ui.Button()
        for name in kwargs.keys():
            value = kwargs[name]
            self.__setattr__(name, value)       
        self.add_subview(self.btn)  

    def __setattr__(self, name, value):     
        print(f'• setattr : {name} = {value}')      
        if name != 'btn':
            self.btn.__setattr__(name, value)           
        super().__setattr__(name, value)

if __name__ == '__main__':

    mainView = ui.View( name='MyButton Demo',
                        bg_color='lightgrey',
                        frame=(0, 0, 400, 400))

    myBtn = MyButton(   name='MyButton', 
                        title='Press me', 
                        width=200)

    myBtn.center = mainView.center
    myBtn.y = 200
    myBtn.background_color = 'red'
    myBtn.tint_color = 'white'

    mainView.add_subview(myBtn)

    mainView.present('sheet')

cvp

@Enez-Houad the problem comes that you set your attributes to both self and self.btn

            self.btn.__setattr__(name, value)       
        super().__setattr__(name, value)

By example, self.y and self.btn.y are set to 200, thus, as height is 100, the button is even outside the ui.View.

The added line at the bottom shows it

    mainView.present('sheet')
    myBtn.btn.frame = (0,0,200,100)