简体   繁体   中英

How to use OOP in Kivy Python?

Please help me, my competition is around the corner
I tried to use OOP in Kivy. This is my simple Python code for testing:

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()

this is my kv file:

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

This is the output

I want the output to be 10 and when the button is pressed the number is added by one.

Please help me, I am new to KIVY

One way of getting pure value from Kivy Property is to use the built-in .get(EventDispatcher obj) method from the kivy.properties.Property class:

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

But before that, you need to import the EventDispatcher class first:

from kivy._event import EventDispatcher

Also please note that while this works in theory and it will indeed change the value of the x variable , I would recommend directly changing the label's own text , something like this:

.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()

Learn more about Kivy Property here and understand how it's not always necessary to use them :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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