如何使用KIvy中的弹出窗口小部件(按钮)从类访问小部件/id



我在从类访问小部件id时遇到问题(此处为SecondWindow(。这个类有一个id为name_btn的按钮,它触发一个弹出窗口,其中有一个id为my_fieldTextInput小部件。我想将SecondWindow中按钮的text更改为用户在文本输入中写入的内容。。。我怎么能那样做。

我尝试使用self.parent.ids.name_btn.text访问按钮的文本,但它在声明AttributeError: 'super' object has no attribute '__getattr__'时出错。如果有任何帮助,我的代码如下>gt;

主.py

import kivy
import kivymd
kivy.require('1.10.1')
from kivymd.app import MDApp
from kivy.uix.screenmanager import ScreenManager , Screen
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.popup import Popup
from kivy.uix.floatlayout import FloatLayout

class Main(Screen):
pass
class SecondWindow(Screen):
name_btn = ObjectProperty(None)
def pop_(self):
pop_up()

class WindowManager(ScreenManager):
pass  
class time_intrvl(FloatLayout): 

my_field = ObjectProperty(None)

def yeah(self):
self.parent.ids.name_btn.text = self.my_field.text

class ExamPortal(MDApp):
def build(self):
kv = Builder.load_file('my.kv')        
return kv

def pop_up():
pop_window = time_intrvl()
PopUpWindow = Popup(title = 'Enter Time' ,content = pop_window,size_hint = (0.5,0.3))
PopUpWindow.open()         

if __name__ == "__main__":
ExamPortal().run()

和my.kv


<time_intrvl>:
my_field : my_field
TextInput:
id : my_field
multiline : False
pos_hint : {'x':0.1 , 'top': 0.74}
size_hint : None,None
size : 200,60
font_size : 26


Button:
size_hint : None , None
text : 'Done'
size : 80,26
font_size : 14    
pos_hint : {'x':0.8,'top':0.18}
on_release:
root.yeah()

WindowManager:
Main:
SecondWindow:

<Main>:
name : 'main'
GridLayout:
cols : 1
Button:

text : 'Go to SecondWindow'
on_release:
app.root.current = 'sec_wind'
<SecondWindow>
name : 'sec_wind'
name_btn : name_btn

GridLayout:
cols : 1
Button:
id : name_btn
text:'Enter Text'
on_release:
root.pop_()                

`

一些小的更改可以使您想要的工作。修改pop_up()以返回PopUpWindow,使其可以关闭:

def pop_up():
pop_window = time_intrvl()
PopUpWindow = Popup(title = 'Enter Time' ,content = pop_window,size_hint = (0.5,0.3))
PopUpWindow.open()
return PopUpWindow

然后修改SecondWindow以保留对PopUpWindow:的引用

class SecondWindow(Screen):
name_btn = ObjectProperty(None)
def pop_(self):
self.popup = pop_up()

最后,修改time_intrvl以修改按钮文本并取消PopUpWindow:

class time_intrvl(FloatLayout):
my_field = ObjectProperty(None)
def yeah(self):
second_window = MDApp.get_running_app().root.get_screen('sec_wind')
second_window.name_btn.text = self.my_field.text
second_window.popup.dismiss()

上面的代码使用MDApp.get_running_app()来获得对App的引用,然后获得Approot,即WindowManager。然后使用CCD_ 19方法来获得对CCD_ 20的引用。通过该引用,我们可以更改Button文本并取消PopUpWindow

相关内容

  • 没有找到相关文章

最新更新