Search code examples
pythonif-statementkivyconditional-statementskivymd

Print which button is pressed KivyMD Python


There are two buttons in my Sample KivyMD Application and I want to print which button is pressed when the button Submit(another button in kv) is pressed (id or text of the button).

I'm trying to do it with if condition. But, if there are any other better ways please let me know.

.kv

MDRoundFlatIconButton:
    icon: "import"
    text: "Arrival"
    id : ar_btn
MDRoundFlatIconButton:
    icon: "export"
    text: "Departure"
    id : dep_btn

Button:
    text: "Submit"
    id : submit_btn
    on_release:
        app.which_clicked()

.py

def which_clicked(self):
    ar_btn = self.root.get_screen('st_rec').ids.ar_btn
    dep_btn = self.root.get_screen('st_rec').ids.dep_btn

    if ar_btn:
        print(ar_btn.text + 'clicked')
    if dep_btn:
        print(dep_btn.text + 'dep clicked')

But it prints both of the button names when one button is pressed.

Arrival clicked
Departure clicked

Then I tried with elif.

def which_clicked(self):
    ar_btn = self.root.get_screen('st_rec').ids.ar_btn
    dep_btn = self.root.get_screen('st_rec').ids.dep_btn

    if ar_btn:
        print(ar_btn.text + 'clicked')
    elif dep_btn:
        print(dep_btn.text + 'dep clicked')

But it prints Arrival clicked all the time (Even I clicked the dep_btn) Please help me for resolve this issue.


Solution

  • In your first function, you checking that Is this button exist ? So you get this output normally. In second one, you checking that is ar_btn exist, and getting onliy Arrival clicked output. Python never return elif if before if statement is true. So in this function, python getting in first if statement and break.

    For check which one clicked you can create one variable and switch it when button click.

    In .py side:

    last_clicked_button = StringProperty('Not clicked yet')
    
    def which_clicked(self):
            print(self.last_clicked_button)
    

    .kv side:

    MDRoundFlatIconButton:
        icon: "import"
        text: "Arrival"
        id : ar_btn
        on_release: app.last_clicked_button = self.text
    MDRoundFlatIconButton:
        icon: "export"
        text: "Departure"
        id : dep_btn
        on_release: app.last_clicked_button = self.text