使KivyMD的MDTextField正常工作

时间:2019-09-17 19:14:21

标签: python android python-3.x kivy kivy-language

你好,所有遇到过KivyMD库的人!

问题是我无法使MDTextField正常工作。 那就是它应该执行的任务:

  1. 用户在MDTextField中输入密钥,然后按 按钮
  2. 如果密钥正确-之后会发生一些变化(例如-toast(“ Key is corrrect!”))
  3. 如果密钥不正确-应该是一个错误(例如-toast('KEY IS INCORRECT!'))
  4. 如果字符过多(例如-超过5个),则必须显示一些内容(例如-toast('Too many text!'))

有main.py:

from kivy.app import App
from kivymd.theming import ThemeManager
from kivymd.label import MDLabel
from kivy.uix.screenmanager import Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.metrics import dp, sp, pt
from kivymd.toast.kivytoast import toast
from kivymd.textfields import MDTextField

class keyinput(MDTextField):
    pass

def toast(text):
    toast(text)

class MyScreen(Screen):

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

        self.menu_items = [
                {
                    "viewclass": "MDMenuItem",
                    "text": "text%d" % i,
                    "callback": self.callback,
                }
                for i in range(1, 3)
            ]

        self.menu_button = None

    def change_variable(self, value):
        print("\nvalue=", value)
        self.VARIABLE = value
        print("\tself.VARIABLE=", self.VARIABLE)

    def callback(self, *args):
        toast(args[0])

class MainApp(App):
    title = "KivyMD MDDropdownMenu Demo"
    theme_cls = ThemeManager()

    def build(self):
        return MyScreen()

    def keycheck(self):
        if keyinput.text == '12345':
            toast('KEY IS CORRECT')
        elif len(keyinput.text) > 5:
            toast('Too much text!')
        else:
            toast('KEY IS INCORRECT!')

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

有main.kv:

#:import MDDropdownMenu kivymd.menus.MDDropdownMenu
#:import MDRaisedButton kivymd.button.MDRaisedButton
#:import MDLabel kivymd.label.MDLabel

<OptionalLabel@MDLabel>:
    halign: 'center'
    font_size: dp(12)

<MDRB@MDRaisedButton>:
    size_hint: None, None
    size: 3 * dp(48), dp(48)
    pos_hint: {'center_x': 0.5, 'center_y': 0.5}
    opposite_colors: True

<keyinput>:
    size_hint_x: 0.5
    halign: 'center'
    pos_hint: {'center_x': .5, 'center_y': .5}
    max_text_length: 5

<MDMenuItem>:
    on_release:
        app.root.change_variable(self.text)
        app.root.menu_button.text = self.text

<MyScreen>:
    name: 'myscrn'
    AnchorLayout:
        anchor_y: 'center'
        BoxLayout:
            orientation: 'vertical'
            size_hint: 0.5, 0.5
            pos_hint: {'center_x': 0.5, 'center_y': 0.5}
            spacing: dp(10)
            MDRB:
                text: 'check the key'
                on_release:
                    app.keycheck()
            keyinput:
                hint_text: "print the key here"

1 个答案:

答案 0 :(得分:0)

  

您需要为您的keyinput小部件分配一个ID。现在看起来   在您的keycheck函数中,它可能不知道输入什么   手段。 kivy.org/doc/stable/guide/lang.html#referencing-widgets

Erik