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

时间:2020-05-09 09:48:28

标签: python kivy

我是kivy和kivyMD的新手,我试图调用一个可以打印用户电子邮件和密码的函数。如何在此代码中绑定函数或使用on_press? 我尝试使用on_pressed:root.function()方法,但是由于我的函数不是用预制的ScreenManager编写的,所以它不起作用

.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”)成功打印“按下”

1 个答案:

答案 0 :(得分:2)

如果您从App类中调用函数,请使用此选项:

on_press: app.doThis()

如果您从Screen类中调用函数,请使用此函数:

on_press: root.doThis()