Understanding Kiwi

I am new to Kivy GUI and I have a few questions related to kvlang:

1. How can I add my own widget class to root in the kv file? (example) PS: I use clear_widgets() , then I try to add my custom widget, but I get an error after clicking the 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 to add a HelloWorldForm class to a widget class using the add_widget method

2. How can I use add_widget and clear_widgets in python code? (eg)

main.kv

  < 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() 

main.py

 #!/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 text from a button. How can i achieve this?

+6
source share
1 answer
  • The problem with this line is: root.add_widget(HelloWorldForm) . You add a class not an instance of the class. In particular, you probably want to add the same instance every 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 HelloWorldForm instance that you defined in the build functions.

  1. This is due to the first question, now you can access the clear_widgets and add_widget functions through the links to helloworldform and mainform that you saved in the build function .:

     self.mainform.clear_widgets() self.mainform.add_widget(self.helloworldform) 
  2. For example, to take the text btnChangeForm:

     self.mainform.btnOpenForm.text = 'This will change the text of the button.' 

It is strange that you do btnOpenForm: btnChangeForm . This will keep the link to btnChagneForm, but the name is btnOpenForm. Why don't they get the same name? btnChangeForm: btnChangeForm

+7
source

Source: https://habr.com/ru/post/975285/


All Articles