我试图从另一个类(这里是 "GetInfoFromAnotherClass")中访问一个类(这里是 "UserInput")的TextInput.text。然而,"Retrieve Info "按钮只给出了初始输入,并没有更新。而在 "UserInput "类中则没有问题--> Button "Get Info"。无论我在文本字段中放入什么,"Retrieve Info"--Button总是返回 "First Input"。我不知道该怎么谷歌了。希望,你们,能帮帮我!
下面是我的一个 "近乎最小 "的问题例子。
import kivy
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
class Container(GridLayout):
pass
class UserInput(BoxLayout):
first_input = ObjectProperty(None)
second_input = ObjectProperty(None)
def __init__(self,**kwargs):
super().__init__(**kwargs)
def ui_btn(self):
print(self.first_input.text)
print(self.second_input.text)
class GetInfoFromAnotherClass(BoxLayout):
def __init__(self,**kwargs):
super().__init__(**kwargs)
self.ui = UserInput()
def retrieve_info(self):
print(self.ui.first_input.text)
print(self.ui.second_input.text)
class MainApp(App):
def build(self):
return Container()
if __name__=='__main__':
MainApp().run()
还有main. kv:
#:kivy 1.11.0
# Well this is just for Beauty ;-)
<MyTextInput@TextInput>:
size_hint_y: None
height: 50
multiline: False
write_tab: False
<MyButton@Button>:
size_hint_y: None
height: 50
<Container>:
cols: 1
UserInput
GetInfoFromAnotherClass
<UserInput>:
first_input: first_input
second_input: second_input
size_hint_y: None
height: self.minimum_height
padding: 20
MyTextInput:
id: first_input
text: "First Entry"
MyTextInput:
id: second_input
text: "Second Entry"
MyButton:
text: "Get Info in the same class"
on_press: root.ui_btn()
<GetInfoFromAnotherClass>:
size_hint_y: None
height: self.minimum_height
padding: 20
MyButton:
text: "Retrieve Info from another Class"
on_press: root.retrieve_info()
该 self.ui = UserInput()
调用创建一个不同的 UserInput
例,一个没有人使用的。
访问文本框的一个方法是这样的。
UserInput
例子<Container>:
cols: 1
UserInput:
id: user_input_box
GetInfoFromAnotherClass:
class GetInfoFromAnotherClass(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.app = App.get_running_app()
# self.ui = UserInput()
def retrieve_info(self):
print(self.app.root.ids.user_input_box.ids.first_input.text)
print(self.app.root.ids.user_input_box.ids.second_input.text)