请帮帮我,我的竞争就要来了
我尝试在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()
输出
我希望输出为10,当按钮被按下时,数字加1。
请帮帮我,我是新来的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变量的值,我建议直接改变标签自己的文本,像这样:
. 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的信息,并了解为什么并不总是需要使用它们:)