Search code examples
pythonkivykivy-language

How to display text when Button is pressed on Kivy


I was wondering how I could make the button I've created on my platform using Kivy, display text when pressed. I want it to display text on the kivy window, not in my integrated terminal. So I was wondering if anyone could help me with that. I want it to display a random dare from my txt file that I have.

Here is my code:

Label:
    text: "Truth or Dare?"
TextInput:
    hint_text: "Two Things To Try: Truth or Dare"
Button:
    text: "Generate"
    on_press: #I dont know what to do here
ScrollView:
Label:

If anyone could help it would be greatly appreciated!


Solution

  • Actually i suggest you to use ScreenManager with kivy.So you can easily use Properties.

    But for this solution you can use that:

    from kivy.app import App
    from kivy.lang import Builder
    kv_string = """
    #:import choice random.choice
    BoxLayout:
        orientation: 'vertical'
        Label:
            id: mylabel
            text: "Truth or Dare?"
        TextInput:
            id: myinput
            hint_text: "Two Things To Try: Truth or Dare"
        Button:
            text: "Generate"
            on_release: root.ids.mylabel.text = choice(app.my_list)
    """
    class MyApp(App):
        def build(self):
            with open('asd.txt', 'r') as mytxt:
                self.my_list = mytxt.readlines()
            return Builder.load_string(kv_string)
    if __name__ == '__main__':
        MyApp().run()