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

时间:2020-10-17 20:30:39

标签: python class popup kivy screen

我在从类(此处SecondWindow)访问小部件ID时遇到问题。此类具有一个ID为name_btn的Button,它将触发一个弹出窗口,该弹出窗口中的ID为TextInput的窗口小部件。我想将my_field中按钮的text更改为用户在textinput中输入的内容...我该怎么做。

我尝试使用self.parent.ids.name_btn.text访问按钮的文本,但这给我一个错误,指出SecondWindow。 请提供任何帮助,我的代码如下>>

main.py

AttributeError: 'super' object has no attribute '__getattr__'

和my.kv

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()

`

1 个答案:

答案 0 :(得分:0)

进行一些小的更改即可得到您想要的工作。修改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来修改Button文本并关闭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的引用,然后获取root(即App)中的WindowManager。然后,它使用get_screen()方法获取对SecondWindow的引用。通过该引用,我们可以更改Button文本并关闭PopUpWindow