繁体   English   中英

如何在 Kivy Python 中使用 OOP?

[英]How to use OOP in Kivy Python?

请帮助我,我的比赛即将来临
我尝试在 Kivy 中使用 OOP。 这是我用于测试的简单 Python 代码:

class location:

    def __init__(self, total_house, total_land):
        self.total_house = total_house
        self.total_land = total_land


class test(BoxLayout):

    def addNum(self):
        App.get_running_app().numberx += 1

class testApp(App):
    x = location(NumericProperty(10),NumericProperty(5))


testApp().run()

这是我的 kv 文件:

<test>:
    orientation: 'vertical'
    Label:
        text: str(app.x.total_house)
    Button:
        text: 'add'
        on_press: root.addNum()

这是输出

我希望输出为 10,当按下按钮时,数字加一。

请帮助我,我是 KIVY 的新手

从 Kivy Property 获取纯值的一种方法是使用kivy.properties.Property类中的内置.get(EventDispatcher obj)方法:

class test(BoxLayout):
    def addNum(self):
        App.get_running_app().x.get(EventDispatcher()) += 1

但在此之前,您需要先导入EventDispatcher类:

from kivy._event import EventDispatcher

另请注意,虽然这在理论上有效并且确实会更改x 变量的值,但我建议直接更改标签自己的 text ,如下所示:

.py

def numberify(*args):
    # This functions is for universally changing str to either int or float
    # so that it doesn't happen to return something like 8.0 which isn't that great
    a = []
    for w in range(0, len(args)):
        try:
            a.append(int(args[w]))
        except ValueError:
            a.append(float(args[w]))
    return a if len(a) > 1 else a[0]

class test(BoxLayout):
    def addNum(self):
        self.ids.label1.text = str(numberify(self.ids.label1.text) + 1)

.kv

<test>:
    orientation: 'vertical'
    Label:
        id: label1
        text: str(app.x.total_house)
    Button:
        id: button1
        text: 'add'
        on_press: root.addNum()

在此处了解有关 Kivy Property 的更多信息并了解并非总是需要使用它们 :)

暂无
暂无

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

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