简体   繁体   中英

How to Bind a button and text input in kivy/kivymd?

I am making an app in kivy/kivymd and I am having some problems.

The program is such that when the user enters the text in the email text field an press enter. The text in the label at the bottom will change to what the user has entered. It worked well.

The files are -

main.py


from kivymd.uix.screen import Screen

from kivy.properties import StringProperty

class DemoApp(MDApp):

    pass

class Screen1(Screen):

    email = StringProperty("Email")

    

    def textInput(self, widget):

        self.email = widget.text

        

    def onClick(self):

        pass
DemoApp().run()

demo.kv


<Screen1>:

    MDTextField:

        hint_text: "Enter your Email"

        pos_hint: {'center_x': 0.5, 'center_y': 0.6}

        on_text_validate: root.textInput(self)

    MDRectangleFlatButton:

        text: "Submit"

        pos_hint: {'center_x': 0.5, 'center_y': 0.5}

        on_press: root.onClick()

    

    MDLabel:

        text: root.email

        halign: "center"

        pos_hint: {'center_y': 0.3}

But I want to bind the button with the text input field such that when the text is entered and the the button is clicked it will print the entered text in the console also run the "on_text_validate" method.

You need to call the textInput function manually in onClick function.

DemoApp.py:

from kivymd.app import MDApp

from kivymd.uix.screen import Screen

from kivy.properties import StringProperty

class DemoApp(MDApp):
    pass

class Screen1(Screen):

    email = StringProperty("Email")

    

    def textInput(self, widget):

        self.email = widget.text

        

    def onClick(self):
        self.textInput(self.ids.text_field)
        print(self.email)


DemoApp().run()

demo.kv:

#:kivy 2.0.0

Screen1:
<Screen1>:

    MDTextField:
        id: text_field

        hint_text: "Enter your Email"

        pos_hint: {'center_x': 0.5, 'center_y': 0.6}

        on_text_validate: root.textInput(self)

    MDRectangleFlatButton:

        text: "Submit"

        pos_hint: {'center_x': 0.5, 'center_y': 0.5}

        on_press: root.onClick()

    

    MDLabel:

        text: root.email

        halign: "center"

        pos_hint: {'center_y': 0.3}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM