I am a newbee with Kivy GUI framework and I have a few questions related to kvlang:
1.How can I add my custom widget class to root in kv file?(example)
PS: I use here clear_widgets()
then I try to add my custom widget but I get error after I click on button.
#:kivy 1.8
<HelloWorldForm@BoxLayout>:
orientation: "vertical"
Label:
text:"Hello world"
Button:
text: "Go back"
on_press: app.formGoBack()
<MainForm@BoxLayout>:
orientation: "vertical"
btnOpenForm: btnChangeForm
BoxLayout:
size_hint_y:None
height:"40dp"
Button:
id:btnChangeForm
text:"Go to hello world form"
on_press:
root.clear_widgets()
root.add_widget(HelloWorldForm)
Button:
id:btnExit
text:"Exit"
on_press: app.Exit()
MainForm:
How can I add HelloWorldForm
widget class using add_widget
method
2.How can I use add_widget
and clear_widgets
methods in python code?(for example)
<MainForm@BoxLayout>:
orientation: "vertical"
btnOpenForm: btnChangeForm
BoxLayout:
size_hint_y:None
height:"40dp"
Button:
id:btnChangeForm
text:"Go to hello world form"
on_press: app.changeForm()
#!/usr/bin/python3.4
import kivy
kivy.require('1.8.0')
from kivy.app import App
from kivy.uix import *
class MainApp(App):
def changeForm(self)
/**
TO-DO
**/
app=MainApp()
app.run()
3.How can I access kvlang properties in python? For example i want to take the text from a button. How can I achieve that?
root.add_widget(HelloWorldForm)
. You are adding a class not a class instance. In particular, you probably want to add the same instance each time it is called rather than creating a new one, so you should not do root.add_widget(HelloWorldForm())
. I suggest that in your python code, add:
class MainApp(App):
def build(self):
self.helloworldform = HelloWorldForm()
self.mainform = MainForm()
return self.mainform
And in your kv replace root.add_widget(HelloWorldForm)
with root.add_widget(app.helloworldform)
This will add the instance of HelloWorldForm that you defined in the build function.
This ties into the first question, you can now access clear_widgets and add_widget functions through the references to helloworldform and mainform you saved in the build function.:
self.mainform.clear_widgets()
self.mainform.add_widget(self.helloworldform)
For example, to take text of btnChangeForm:
self.mainform.btnOpenForm.text = 'This will change the text of the button.'
It is strange that you do btnOpenForm: btnChangeForm
. This will save a reference to btnChagneForm but name is btnOpenForm. Why not have them the same name? btnChangeForm: btnChangeForm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With