【问题标题】:How to use OOP in Kivy Python?如何在 Kivy Python 中使用 OOP?
【发布时间】:2021-10-26 01:46:01
【问题描述】:

请帮助我,我的竞争即将来临
我尝试在 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().x.total_house += 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()

This is the output

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

请帮帮我,我是 KIVY 的新手

【问题讨论】:

  • 你试过用x = location(10, 5)替换x = location(NumericProperty(10),NumericProperty(5))吗?
  • numberx 是什么?
  • @RufusVS 抱歉,实际上是 x.total_house
  • @Weebify 如果我用位置 (10,5) 替换它,我无法将它们添加 1。即使我按下按钮,它也会显示 10 和 5。 (对不起我的英语不好)
  • 你检查我的答案了吗?

标签: python python-3.x kivy kivy-language kivymd


【解决方案1】:

从 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 变量的值,但我建议直接更改 标签自己的文本,例如这个:

.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 here 的更多信息,并了解并非总是需要使用它们 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多