简体   繁体   English

如何在单击按钮时更新 kivy 中的 Label

[英]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.每个按钮 class 和每个从按钮 class 继承的 class 都有一个 on_press 方法。

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.您基本上有两种可能性,或者您编写自己的自定义按钮 class 并覆盖此 class 中的 on_press 方法,或者您编写自定义方法并将此方法分配给按钮属性 on_press ,就像我在本示例中所做的那样。 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.还有一个 on_release 方法,您可以使用与 on_press 方法相同的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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