简体   繁体   中英

How to Update Label in kivy On Clicking a Button

I am Really Tired of Searching Related to This Topic. And never Getting Something Great Answer...

I am sorry to say that, but then you should question your search skills. Please provide next time a minimal example of what you already tried, because then I could help you with proper understanding the mechanisms. Of course, I could simply give you a solution, but this would not help you at all, because often there are different ways to get to the same result but in some situations, you should prefer one method to the other ones.

Back to your problem

Here is a simple example:

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

class MyApp(App):
    def build(self):
        self.layout = BoxLayout()
        self.btn = Button(text="press", on_press=self.my_btn_method)
        self.lbl = Label(text="")
        self.layout.add_widget(self.btn)
        self.layout.add_widget(self.lbl)

        return self.layout

    def my_btn_method(self, instance):
        self.lbl.text = str(random.randint(0,100))

MyApp().run()

Explanation:

Every Button class and every class that inherits from the Button class has a on_press method.

You have basically two possibilities, either you write your own custom button class an overwrite the on_press method within this class or you write a custom method and assign this method to the buttons attribute on_press as I did in this example. When you do this, your custom method has to take the button instance as an attribute.

To change the labels text I simply assigned a new string to the labels text attribute. I really hope, this helps you with your problem. If you have some struggle just write a comment and I try to help you.

There is also an on_release method which you can use in the same way as the on_press method.

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