如何将文本输入数据收集为要在If语句中使用的变量

时间:2018-12-30 02:45:30

标签: python kivy

我需要了解在kivy文本框中收集用户输入数据的语法,其目的是使登录按钮像应该的那样位于屏幕功能的左下角。我想使程序能够收集用户在密码字段中输入的内容,然后使用if语句确定密码是否正确。

我知道这是有可能的,我只是不知道使用什么语法,并且文档在文本框上讨论不多。

Python文件:

import kivy
from kivy.app import App
kivy.require("1.10.1")
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.uix.screenmanager import ScreenManager
from kivy.uix.textinput import TextInput

class Screen1(Screen):
    pass

class Screen2(Screen):
    pass

class ScreenManager(ScreenManager):
    pass

render = Builder.load_file("kvinterp.kv")

class MainApp(App):

    def build(self):
        return render

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

.kv文件:

ScreenManager:
    Screen1:
    Screen2:

<Screen1>:
    name: "Screen1"
    Label:
        text: "Please Enter The Correct Password"
        pos_hint: {"x": .45, 'y':.9}
        size_hint: .1, .1
        font_size: 40
    TextInput:
        hint_text: "Password"
        size_hint: 0.3, 0.1
        pos_hint: {"x": 0.35, 'y': 0.5}
        multiline: False
    Button:
        text: "Login"
        on_release: app.root.current = "Screen2"
        size_hint: 0.17, 0.16
        pos_hint: {"x": 0, 'y':0}
        background_color: 1.23, 1.56, 1.70, .5

<Screen2>:
    name: "Screen2"
    Label:
        text: "You've Logged In!"
    Button:
        text: "Return"
        on_release: app.root.current = "Screen1"
        size_hint: 0.17, 0.16
        pos_hint: {"x": 0, 'y':0}
        background_color: 1.23, 1.56, 1.70, .5

1 个答案:

答案 0 :(得分:2)

想法是在按下按钮时将文本传递给函数,但要标识元素,必须建立id

*。py

# ...

class Screen1(Screen):
    def validate_password(self, password):
        if password == "123456":
            self.manager.current = "Screen2"

# ...

*。kv

# ...

<Screen1>:
    name: "Screen1"
    Label:
        text: "Please Enter The Correct Password"
        pos_hint: {"x": .45, 'y':.9}
        size_hint: .1, .1
        font_size: 40
    TextInput:
        id: password_ti # <---
        hint_text: "Password"
        size_hint: 0.3, 0.1
        pos_hint: {"x": 0.35, 'y': 0.5}
        multiline: False
    Button:
        text: "Login"
        on_press: root.validate_password(password_ti.text) # <---
        size_hint: 0.17, 0.16
        pos_hint: {"x": 0, 'y':0}
        background_color: 1.23, 1.56, 1.70, .5

# ...