kivy import kivy code example

Example 1: kivy sample code

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput


class LoginScreen(GridLayout):

    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.cols = 2
        self.add_widget(Label(text='User Name'))
        self.username = TextInput(multiline=False)
        self.add_widget(self.username)
        self.add_widget(Label(text='password'))
        self.password = TextInput(password=True, multiline=False)
        self.add_widget(self.password)


class MyApp(App):

    def build(self):
        return LoginScreen()


if __name__ == '__main__':
    MyApp().run()

Example 2: how to change a kivy button text in kivy lang from python file

from kivy.app import App
from kivy.lang.builder import Builder
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout


class Container(BoxLayout):
    message = StringProperty()

    def retranslate(self, language):
        texts = {"en": "Hello World", "fr": "Salut monde"}
        self.message = texts.get(language, "")


Builder.load_string(
    """
<Container>:
    orientation: 'vertical'
    Button:
        text: root.message
    Button:
        text: "Eng"
        on_press: root.retranslate("en")
    Button:
        text: "Fra"
        on_press: root.retranslate("fr")
"""
)


class MyApp(App):
    def build(self):
        w = Container()
        w.retranslate("en")
        return w


if __name__ == "__main__":
    MyApp().run()

Tags:

Misc Example