简体   繁体   中英

Loading one line of text from file to Kivy label

I want to make a simple program that is just showing definitions that are stored in text file.One label and button to show next definition. I try to do it with documentation but i cannot find how to load text into label. Can someone show me to some good resources or code samples ?

My code for now (i want to build in on top of example from kivy website):

import kivy
kivy.require('1.9.0')

from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
    def build(self):
        return Label(text = 'Hello world')

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

The easiest way to update widgets in the UI are by binding to their properties . This can be done in code, but the real power of kivy in my opinion comes from using it's declarative UI language . Using kv, you get automatic binding.

Here is a quick example of what you might do:

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import StringProperty

kv = '''

BoxLayout:
    orientation: 'vertical'
    Label:
        text: app.text
    Button:
        text: 'click me'
        on_press: app.clicked()

'''


class MyApp(App):
    text = StringProperty("hello world")

    def build(self):
        return Builder.load_string(kv)

    def clicked(self):
        self.text = "clicked!"


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

In the kv description of the UI, you tell kivy that you want the text on the Label to be bound to a StringProperty on the app which you defined on the class. The auto-binding means that anytime you set a value to that property (like in the clicked function), the UI will update with the new value automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM