如何从py文件(kivymd2.0.1)中的MDialog()内的MDTextField获取值

问题描述 投票:0回答:2

我想获取MDTextField中文本的值。在 .kv 中,您只需使用 id 作为参考,如下所示:

id : my_text

但是,在 py 文件内的 MDialog() 中,您使用 = 而不是 : ,并且许多值您只需将它们作为“”或在 () 之间传递。 但有了 id,我不知道该怎么办。 看,这就是例子:

from kivy.config import Config
Config.set('graphics', 'width', '375')
Config.set('graphics', 'height', '650')
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivymd.uix.button import MDButton, MDButtonText
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.textfield import (
    MDTextField,
    MDTextFieldHintText,
)
from kivymd.uix.dialog import (
    MDDialog,
    MDDialogButtonContainer,
    MDDialogContentContainer,
)

class MyBL1(BoxLayout):
    dialog = None
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def challenge_friend(self):
        if not self.dialog:
            self.dialog = MDDialog(
                MDDialogContentContainer(
                   MDTextField(
                        MDTextFieldHintText(
                            text= "Usuario",
                        ),
                    #id='tipo', #?????
                    mode= "outlined",
                   ),  
                pos_hint= {'center_x': 0.5},      
                orientation="vertical",
                spacing = "10dp",
                ),   
            MDDialogButtonContainer(
                Widget(),
                MDButton(
                    MDButtonText(text="Cancel"),
                    style="text",
                    #on_release = self.stop_challenge,
                ),
                MDButton(
                    MDButtonText(text="Aceptar"),
                    style="text",
                    #on_release = self.create_challenge()
                ),
            size_hint_x = 1,         
            spacing="10dp",
        ),
        )
        self.dialog.open()
    
    def create_challenge(self, *args):
        usuario = self.ids.tipo.text  #???
        print(usuario)   #?????
        self.dialog.dismiss()
        self.dialog = None

KV = """
<MyBL1>
    Button:
        font_size: "30sp"
        text: "Create Dialog"
        on_release: root.challenge_friend()
"""
Builder.load_string(KV)

class MyApp(MDApp):

    def build(self):
        self.screenm = ScreenManager()
        self.mybl_uno = MyBL1()
        screen = Screen(name="first screen")
        screen.add_widget(self.mybl_uno)
        self.screenm.add_widget(screen)
        return self.screenm


MyApp().run()

如您所见,我尝试将 id 引用设置为 '' 但是,这不起作用。顺便说一下 id=tipo,不起作用 在这种情况下我怎样才能完成这个任务? 谢谢!

kivy kivymd
2个回答
1
投票

另一种方法是使用

kv
语言和
ids
。这是使用此方法的代码的修改版本:

from kivy.config import Config
from kivy.properties import ObjectProperty

Config.set('graphics', 'width', '375')
Config.set('graphics', 'height', '650')
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.dialog import (
    MDDialog
)

# My extension of MDDialog
class MyDialog(MDDialog):
    mybl1 = ObjectProperty(None)


class MyBL1(BoxLayout):
    dialog = None

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def challenge_friend(self):
        if not self.dialog:
            self.dialog = MyDialog(mybl1=self)  # create MyDialog instead of MDDialog
        self.dialog.open()

    def create_challenge(self, *args):
        usuario = self.dialog.ids.tipo.text
        print(usuario)
        self.dialog.dismiss()
        self.dialog = None


KV = """
<MyBL1>
    Button:
        font_size: "30sp"
        text: "Create Dialog"
        on_release: root.challenge_friend()
        
<MyDialog>:
    MDDialogContentContainer:
        pos_hint: {'center_x': 0.5}
        orientation: "vertical"
        spacing: "10dp"
        MDTextField:
            id: tipo
            mode: "outlined"
            MDTextFieldHintText:
                text: "Usuario"
    MDDialogButtonContainer:
        size_hint_x: 1
        spacing: "10dp"
        Widget:
        MDButton:
            on_release: root.mybl1.stop_challenge()
            MDButtonText:
                text: "Cancel"
                style: "text"
        MDButton:
            on_release: root.mybl1.create_challenge()
            MDButtonText:
                text: "Aceptar"
                style: "text"
            
"""
Builder.load_string(KV)


class MyApp(MDApp):

    def build(self):
        self.screenm = ScreenManager()
        self.mybl_uno = MyBL1()
        screen = Screen(name="first screen")
        screen.add_widget(self.mybl_uno)
        self.screenm.add_widget(screen)
        return self.screenm


MyApp().run()

1
投票

执行您想要的操作的一个简单方法是保存对

MDTextField
的引用。尝试将您的
challenge_friend()
方法更改为:

def challenge_friend(self):
    if not self.dialog:
        # create the MDTextField and save a reference to it
        self.text_field = MDTextField(
                    MDTextFieldHintText(
                        text="Usuario",
                    ),
                    mode="outlined"
        )

        self.dialog = MDDialog(
            MDDialogContentContainer(
                self.text_field,  # use the MDTextField created above
                pos_hint={'center_x': 0.5},
                orientation="vertical",
                spacing="10dp",
            ),
            MDDialogButtonContainer(
                Widget(),
                MDButton(
                    MDButtonText(text="Cancel"),
                    style="text",
                    # on_release = self.stop_challenge,
                ),
                MDButton(
                    MDButtonText(text="Aceptar"),
                    style="text",
                    on_release = self.create_challenge
                ),
                size_hint_x=1,
                spacing="10dp",
            ),
        )
    self.dialog.open()

那么你的

create_challenge()
方法可以是:

def create_challenge(self, button):
    usuario = self.text_field.text  # ???
    print(usuario)  # ?????
    self.dialog.dismiss()
    self.dialog = None
    self.text_field = None

仅当您使用

ids
语言时才会创建
kv
字典。如果您需要跟踪多个
ids
词典,您可以创建自己的词典。然而,创建的
kv
是弱引用,因此它们不会阻止字典中的小部件被垃圾收集。
    

© www.soinside.com 2019 - 2024. All rights reserved.