How to change text of a label in the kivy language with python

前端 未结 1 1834
暗喜
暗喜 2020-12-11 01:25

I was wondering how I could change the text of a label made inside the Kivy language using Python. Like how would I have user input from python be made as the text of a labe

相关标签:
1条回答
  • 2020-12-11 01:48

    Text of a label can be a kivy property, which can be later changed and since it is a kivy property it will automatically updated everywhere. Here is an example of your .py

    from kivy.app import App
    from kivy.uix.widget import Widget
    from kivy.properties import StringProperty
    import random
    
    class YourWidget(Widget):
        random_number = StringProperty()
    
        def __init__(self, **kwargs):
            super(YourWidget, self).__init__(**kwargs)
            self.random_number = str(random.randint(1, 100))
    
        def change_text(self):
            self.random_number = str(random.randint(1, 100))
    
    class YourApp(App):
        def build(self):
            return YourWidget()
    
    if __name__ == '__main__':
        YourApp().run()
    

    and your .kv

    <YourWidget>:
        BoxLayout:
            size: root.size
            Button:
                id: button1
                text: "Change text"
                on_release: root.change_text()
            Label:
                id: label1
                text: root.random_number
    

    When you click the button, it will call change_text() function, which will randomly change the text of the label to random integer between 1 and 100.

    0 讨论(0)
提交回复
热议问题