Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Missing something
-
I am using Pythonista 3
I have made a pyui file with a button and a label.
In my py file I have a defined a function for button action.
I want the function to change the text in the label.
Now I am stuck, what am I missing?
If you think you can help, thank you 😊 -
It is easier to debug Python code than English prose. Could you please post the code in a gist or repo or here?
-
import ui def hit_button(sender): textfield1.text = 'Hello' ui.load_view('My UI').present('sheet')
NameError: name 'textfield1' is not defined
-
@BlockSweeps By default, the views loaded from your UI file aren't available as Python variables. If you want to access your views from Python, you need to store the root view (returned from
ui.load_view
) in a variable and use that to access the other views:import ui def hit_button(sender): # root['textfield1'] means "root's subview with the name textfield1" root['textfield1'].text = 'Hello' root = ui.load_view('My UI') root.present('sheet')
-
@dgelessus thank you for you response. My ui is now working.
I don't fully understand how, but I will go back to the tutorial and work it out.
Thank you once again -
@BlockSweeps , have a look at superview in the docs. Almost all ui elements such as buttons etc are views themselves, in that they are subclassed from ui.View. @dgelessus solution is fine. root in this case is your view. The root['textfield1'] is just retrieving the textfield1 ui object. You can print it. So to simplify you could have done tf = root['textfield1'] then tf.text = 'Hello' or tf.bg_color = 'blue' for example.
Anyway, sender is actually a ui.Button object. You can also print it to confirm. As I mentioned almost all the ui elements are subclassed from ui.View. All views have an attr called superview. The superview for an item is the view it resides in. So sender.superview is in the case root. As the button is contained in that view. So your hit_button func could have be written likedef hit_button(sender): sender.superview['textfield1'].text = 'Hello'
You can see in this case you didn't need access to your root var.
Its really worth reading of the ui.View docs and doing some tests just to feel comfortable with it. Eg, every view has attr called subviews. This enables you to iterate over all the subviews in your view for example.
Hope this helps a little -
@Phuket2 thanks for your reply and comments.
I had played a little with tkinter befor trying pythonista. There, I made a frame called root and placed all of my widgets in the root.
When I start to think of parent child relationships at different levels, things are starting to make sense.
I will read up on superview.Thank you