简体   繁体   中英

Kivy: How can I connect TextInput in .KV file to a variable in Python?

I'm trying to create a simple login page for this app using Kivy.

I'm new to this, and I'm wondering how I can connect the Email TextInput to a variable ( email_catch ) in my python code, similar to a normal.get() function.

Python Code

from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty, StringProperty



class Login_Window(Screen):


    def verify(self):
        email_catch = self.root.ids.email.text
        print(email_catch)

class MyApp(App):
    def build(self):
        return Login_Window()


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

.KV File

#:kivy 2.0.0

<Login_Window>:
    GridLayout:
        cols:1
        size: root.width, root.height

        GridLayout:
            cols:2

            Label:
                text: 'Email'
            TextInput:
                multiline: False
                id: email

        Button:
            text: 'Log In'
            on_press: root.verify()

Since you are calling root in verify method of Login_Window class (where it ( root ) hasn't been defined yet) and not in the build method of the App class you are supposed to get an AttributeError .

In order to access an id within that class you should use self.ids . So the change you need:

    def verify(self):
        email_catch = self.ids.email.text
        print(email_catch)

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