簡體   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