from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.label import Label
Balance = 0
Balance_string = str(Balance)
class MyWidget(Widget):
def ads(self):
global Balance
Balance += 0.25
Balance_string = str(Balance)
print(Balance_string)
return Balance_string
class BuzzMoneyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
BuzzMoneyApp().run()**我的.kv文件**
<MyWidget>:
canvas:
Color:
rgb: (0, 150,0)
Rectangle:
pos: self.pos
size: self.size
Button:
center: self.parent.center
font_size: 14
height: 28
background_color: (1.0, 0.0, 0.0, 1.0)
text: "Earn money"
on_press:root.ads()我想从我的main.py中访问.kv文件中的Balance字符串变量,这样我就可以在屏幕上显示它。
发布于 2022-04-22 02:26:21
您可以轻松地从Properties内部的python中引用kv。下面是您的代码的修改版本,可以这样做:
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import NumericProperty, StringProperty
from kivy.uix.widget import Widget
# Balance = 0
# Balance_string = str(Balance)
class MyWidget(Widget):
Balance = NumericProperty(0)
Balance_string = StringProperty('0')
def ads(self):
self.Balance += 0.25
print(self.Balance_string)
def on_Balance(self, *args):
# update Balance_string whenever Balance changes
self.Balance_string = str(self.Balance)
class BuzzMoneyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
BuzzMoneyApp().run()然后可以在Properties中引用kv中的那些
<MyWidget>:
canvas:
Color:
rgb: (0, 150,0)
Rectangle:
pos: self.pos
size: self.size
Button:
center: self.parent.center
font_size: 14
height: 28
background_color: (1.0, 0.0, 0.0, 1.0)
text: "Earn money"
on_press:root.ads()
Label:
text: root.Balance_string # root.Balance_string can be replaced with just str(root.Balance)
size_hint: None, None
size: self.texture_size
pos: 300, 200
color: 0,0,0,1Properties必须在EventDispatcher (通常是Widget)中定义。on_Balance()方法在Balance Property更改时自动触发,并更新Balance_string Property。如图所示,Balance_string可以在kv中使用,每当Balance_string Property发生变化时,Label将被更新。因为Balance_string只是Balance的字符串值,所以可以在kv中消除它并替换为str(root.Balance)。
https://stackoverflow.com/questions/71958109
复制相似问题