我想访问从main类到fahim2_pop类的ID。想要访问从textinput(在主类中)到弹出窗口小部件的单词,该窗口小部件将在有人按下搜索按钮时显示。当有人搜索“ hello”并按搜索按钮时,将出现弹出窗口小部件,并且在该弹出窗口小部件中,标签的文本将为“ hello”,与来自文本输入的相同。但标签和ID仍在不同的类中。怎么做?
python代码
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.properties import *
class fahim2_pop(Popup):
pass
class main(BoxLayout):
def word(self):
pop=fahim2_pop()
pop.open()
class go(BoxLayout):
def main(self):
self.clear_widgets()
self.add_widget(main())
class CallApp(App):
def build(self):
return go()
CallApp().run()
kv代码
Builder.load_string('''
<main>:
BoxLayout:
orientation:"vertical"
TextInput:
id:word
Button:
text:"search"
on_press:root.word()
<go>:
Button:
text:"go"
on_press:root.go()
<fahim2_pop>:
id:pop
title:"result"
BoxLayout:
Label:
text:app.root.ids.word.text
''')
我知道app.root.ids.word.text,如果该ID保留在我的应用程序的根目录中。但这里是应用程序的根源。如何从fahim2_pop类的main类中访问ID?
答案 0 :(得分:1)
有两种方法可以解决此问题。解决方案之一如下:
main()
中的方法go()
重命名为go()
,因为在您的kv文件中,您已绑定on_press: root.go()
main()
并将其存储在类属性main
from kivy.properties import ObjectProperty
...
class go(BoxLayout):
main = ObjectProperty(None) # declare class attribute
def go(self):
self.clear_widgets()
self.main = main()
self.add_widget(self.main)
text:app.root.ids.word.text
替换为text:app.root.main.ids.word.text
<fahim2_pop>:
...
Label:
text:app.root.main.ids.word.text
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty
Builder.load_string('''
<main>:
BoxLayout:
orientation:"vertical"
TextInput:
id:word
Button:
text:"search"
on_press:root.word()
<go>:
Button:
text:"go"
on_press:root.go()
<fahim2_pop>:
id:pop
title:"result"
BoxLayout:
Label:
text:app.root.main.ids.word.text
''')
class fahim2_pop(Popup):
pass
class main(BoxLayout):
def word(self):
pop = fahim2_pop()
pop.open()
class go(BoxLayout):
main = ObjectProperty(None)
def go(self):
self.clear_widgets()
self.main = main()
self.add_widget(self.main)
class CallApp(App):
def build(self):
return go()
CallApp().run()