Forum Archive

how to access label variable in def?

ryubai

when I run these code, it shows a error name lib is not defineded?

how to slove? thanks

import ui
from objc_util import *

def change(sender):
lb.text='new'

@on_main_thread
def main():
v=ui.View()
v.background_color='white'

lb=ui.Label(text='old')
btn=ui.Button(title='press',action=change)

v.add_subview(lb)
v.add_subview(btn)

v.present()

if name=='main':
main()

JonB

When you post code, can you add in the three backticks before and after, like this

```
import something
def main():
   ...

```

That way, we can see the proper indenting.

JonB

The reason is that you have defined lb inside a function -- main(), not as a global.

Either use globals, or use attributes directly accessible from your UI elements. Sender in your code will be the button--so sender.superview leads to your main view in this case, and sender.superview.lb.text='test' etc let's you store info in your own custom attribute names. Just be sure they are unique names that are not already attributes of ui.View.

When you are trying into to access subviews you can do

sender.superview['label1'].text='test'

if you originally define view names when you add them to your main view.
Or, you can add attributes of the button to point to it's target label,

B=ui.Button(...)
L=ui.Label()

B.target_label=L
...
#Then in your callback
sender.target_label.text='...'
cvp

@ryubai same kind of solution

import ui
from objc_util import *

def change(sender):
    sender.superview['lb'].text='new'

@on_main_thread
def main():
    v=ui.View()
    v.background_color='white'

    lb=ui.Label(name='lb', text='old')
    btn=ui.Button(title='press',action=change)

    v.add_subview(lb)
    v.add_subview(btn)

    v.present()
if __name__=='__main__':
    main()
ryubai

thanks to you all. sloved!
and sorry for my wrong code format,i'll correct it in my next post.

doithuong

I am also interested in this question, thanks for your answer.