繁体   English   中英

Python / Kivy - 如何在kv / py文件中“连接”函数和标签

[英]Python/Kivy - How to “connect” a function and a label in kv/py files

我在类中创建了一个计数器来增加count的值

count = 0

class LifeCounterApp(App):
    def incr(n):
        global count 
        count += 1
        return count

我有一个kv文件,我在其中创建我的应用程序的结构。

我想做什么:我的应用程序内的按钮“+”必须更新Label的值。

示例:标签的默认值为0 如果我单击按钮,标签必须将其值更改为1 ,依此类推。

我的问题:

1)如何从.py文件中获取标签的值?

2)我调用函数incr是正确的吗? 因为实际点击按钮没有任何反应。

Button:
    text: "+"
    on_release:
        app.incr()
Label:
    text: app.count (?)

希望我的问题清晰明确。

您应该使用NumericProperty而不是Python全局变量。

例:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder


Builder.load_string('''
<LifeCounter>:
    BoxLayout:
        orientation: "vertical"

        Button:
            text: "+"
            on_release: root.count += 1
        Label:
            id: l_label
            text: str(root.count)

''')


class LifeCounter(BoxLayout):
    count = NumericProperty(0)
    def __init__(self, **kwargs):
        super(LifeCounter, self).__init__(**kwargs)

class DemoApp(App):
    def build(self):
        return LifeCounter()

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

如果你想使用incr方法来增加count的值,你可以这样做:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder


Builder.load_string('''
<LifeCounter>:
    BoxLayout:
        orientation: "vertical"

        Button:
            text: "+"
            on_release: root.incr()
        Label:
            id: l_label
            text: str(root.count)

''')


class LifeCounter(BoxLayout):
    count = NumericProperty(0)
    def __init__(self, **kwargs):
        super(LifeCounter, self).__init__(**kwargs)

    def incr(self):
        self.count += 1

class DemoApp(App):
    def build(self):
        return LifeCounter()

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

暂无
暂无

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

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