尝试弄清楚与setter的绑定如何在kivy中工作。我发现API中的文档非常糟糕。他们非常期望围绕他们的kivy引擎有大量的假设知识。
无论如何,咆哮。这是我的代码。
class ScreenOne(Screen):
story = StringProperty('')
def __init__ (self,**kwargs):
super (ScreenOne, self).__init__(**kwargs)
Buttonlayout = GridLayout(orientation='vertical',cols=1, spacing=2, size_hint_y=None)
Buttonlayout.bind(minimum_height=Buttonlayout.setter('height'))
btn = Button(text="change the text", size_hint_y=None, height=80,text_size=(350,None),font_size='12sp')
btn.bind(on_press=partial(self.changer,"text has changed"))
Buttonlayout.add_widget(btn)
root.add_widget(Buttonlayout)
self.add_widget(root)
def changer(self,*args):
self.story = args[0]
self.manager.current = 'screen2'
class ScreenTwo(Screen):
def __init__(self,**kwargs):
super (ScreenTwo,self).__init__(**kwargs)
my_box1 = BoxLayout(orientation='vertical')
L1 = Label(text=self.screenOne.story,font_size='24dp')
L1.bind(self.L1.setter('text')= story)
my_button1 = Button(text="Go to screen 1",size_hint_y=None, size_y=100)
my_button1.bind(on_press=self.changer)
my_box1.add_widget(self.L1)
my_box1.add_widget(my_button1)
self.add_widget(my_box1)
def changer(self,*args):
self.manager.current = 'screen1'
我的想法是当我按下类screenOne中的按钮并更改屏幕时,它应该更改screenTwo中的标签。我认为最好的方法是使用Properties,然后将标签绑定到StringProperty中的更改。我可以很好地改变故事中的字符串,如果我向它添加打印指令,我可以看到它发生了变化。它只是更新我遇到问题的标签。
我似乎无法让它发挥作用。非常感谢帮助和指导。
答案 0 :(得分:1)
请注意,只能使用kv
语言(几乎)完全实现所需的行为:
myapp.py
:
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty, ObjectProperty
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.app import App
class ScreenOne(Screen):
story = StringProperty('')
def changer(self,*args):
self.story += args[0]
self.manager.current = 'screen2'
class ScreenTwo(Screen):
pass
class MyApp(App):
pass
if __name__ == '__main__':
MyApp().run()
和my.kv
:
ScreenManager:
ScreenOne:
id: screen_one
name: 'screen1'
GridLayout:
orientation:'vertical'
cols:1
spacing:2
size_hint_y:None
on_minimum_height: self.setter('height')
Button:
text:"change the text"
size_hint_y:None
height: 80
text_size: (350,None)
font_size: '12sp'
on_press: screen_one.changer("text ")
ScreenTwo:
name: 'screen2'
BoxLayout:
orientation: 'vertical'
Label:
id: L1
text: screen_one.story
font_size: '24dp'
Button:
text: "Go to screen 1"
size_hint_y: None
size_y:100
on_press: root.current = 'screen1'
但是,如果您想使用Label
的setter,请更改MyApp
类定义:
class MyApp(App):
def build(self):
print self.root.ids
S1 = self.root.ids['screen_one']
L1 = self.root.ids['L1']
S1.bind(story=L1.setter('text'))
并确保Label
的{{1}}是静态的:text
。