Python KivyMD:如何使用按钮调用一个函数?

问题描述 投票:0回答:1

我是kivy和kivyMD的新手,我想调用一个函数来打印用户的电子邮件和密码。我怎么能在这段代码中绑定函数或使用on_press呢?

.PY

import...
Builder.load_string("""
   #:include kv/login.kv
   #:import utils kivy.utils 
   #:import images_path kivymd.images_path
""")

class MyApp(MDApp):
    def __init__(self, **kwargs):
        self.title = "iKarate"
        self.theme_cls.theme_style = "Light"
        self.theme_cls.primary_palette = "Blue"
        self.sm = ScreenManager()
        super().__init__(**kwargs)

    def build(self):
        self.sm.add_widget(Factory.LoginScreen())

        return self.sm

    def doThis(self):
        email = self.email
        password = self.password
        print(email, password)

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

.KV

#:kivy 1.11.1
<LoginScreen@Screen>:
    name: "login"

    BackgroundLayer:

    #MDCard:
    MDCard:
        orientation: "vertical"
        size_hint: [0.8, 0.6]
        pos_hint: {"center_x": 0.5, "center_y": 0.6}
        BoxLayout:
            orientation: "vertical"
            MDLabel:
                text: "Welcome to the log in page"
                text_size: self.size
                font_size: 25
                bold: True
                halign: "center"
                valign: "middle"

            Image:
                size_hint_y: 10
                source: "kv/image.png"

            MDTextField:
                id: email
                hint_text: "E-mail"

            MDTextField:
                id: password
                hint_text: "Password"
                password: True

            MDFillRoundFlatButton:
                id: btn
                text: "Sign In"
                width: dp(200)
                pos_hint: {"center_x": .5}
                on_press:print("pressed")

<BackgroundLayer@BoxLayout>:
    orientation: "vertical"
    BoxLayout:
        orientation: "vertical"
        canvas.before:
            Color:
                rgba: utils.get_color_from_hex("#00146e")
            Rectangle:
                pos: 0, self.center_y + self.height/3 - 50
                size: (self.width,70)

    BoxLayout:
        orientation: "horizontal"

on_press:print("pressed") 成功打印 "pressed"

python kivy
1个回答
0
投票

如果你调用一个函数,请使用这个 App 类。

on_press: app.doThis()

如果你调用一个来自 Screen 类。

on_press: root.doThis()
© www.soinside.com 2019 - 2024. All rights reserved.