Zenast
Zenast

Reputation: 61

Python KivyMD: how to call a function using a button?

im new to kivy and kivyMD, and i was trying to call a function that would print the email and password of a user. how would can i bind the function or use on_press in this code? i tried using on_pressed:root.function() method, but it doesnt work since my function is not written in the pr-emade 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") successfully prints "pressed"

Upvotes: 2

Views: 5406

Answers (1)

Fyzzy good
Fyzzy good

Reputation: 102

Use this if you call a function from App class:

on_press: app.doThis()

And use this if you call a function from Screen class:

on_press: root.doThis()

Upvotes: 3

Related Questions