我想获取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,不起作用 在这种情况下我怎样才能完成这个任务? 谢谢!
执行您想要的操作的一个简单方法是保存对
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