H
H
HyperChan2021-04-29 01:53:19
Python
HyperChan, 2021-04-29 01:53:19

How to change the text in Label on button click?

How can I change the text in the label when the button is clicked?

import kivy

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout


class TestApp(App):

    def build(self):
        bl = BoxLayout
        bl.add_widget(Button(text="Hello"))
        bl.add_widget(Label(text="Hello World"))


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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
EmeraldGuy, 2021-05-02
@HyperChan

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout


class TestApp(App):

    def change_text(self, instance):
        self.label.text = "Text Was Changed"

    def build(self):
        bl = BoxLayout()
        self.label = Label(text="Hello World")
        bl.add_widget(Button(text="Hello", on_press=self.change_text))
        bl.add_widget(self.label)

        return bl

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

1. It is necessary to add the instance argument to the function.
2. In order to be able to change the text when the button is pressed, it is necessary not immediately through Add_Widget, but first add it to a variable, you must put .self before the variable name to change the text

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question