Changing a label based on boolean condition in Kivy application

Viewed 400

In an application I'm working on in Kivy Python, I'm trying to input a simple start/stop button. Click to start what theoretically will be a timer, and then stop it when the activity is complete. For proof of concept, I just wanted the start button to be clicked and changed to "stop" (and show a corresponding popup stating "activity started"), and subsequently the reverse when the stop button is clicked.

Still being novice overall, I wanted to do this via a boolean condition with a variable called "activity_choice". The problem is, this logic will work once and then I can't change the label back and forth in subsequent clicks. The likely issue is the Kivy application never knows that the boolean variable is actually changed (and does not update it in real-time). Is there a better way to go about this versus a boolean variable? Or is there a way to potentially refresh the application for it to realize the boolean has changed?

.py file code:

    def activity_popup(self):
    if self.activity_choice == False:
        self.activity_choice == True
        activity_label = self.root.ids['add_workout_screen'].ids['activity_label']
        activity_label.text = "Stop Activity"

        
    if self.activity_choice == True:
        self.activity_choice == False
        activity_label = self.root.ids['add_workout_screen'].ids['activity_label']
        activity_label.text = "Start Activity"

.kv file code:

    GridLayout:             
        rows: 2
        pos_hint: {"top": .55, "right": 1.0}
        size_hint: 1, .26
        ImageButton:
            source: "icons/power.png"
            on_press: app.activity_popup()

        LabelButton:
            size_hint: .3, .2
            pos_hint: {"top": .45, "right": 1.0}
            text: "Start Activity"
            id: activity_label
            on_press: app.activity_popup()
1 Answers

You can change the label text based on button text which is also changed on on_press event like below example. You can also choose to open a popup in the on_press event (not shown in the example).

from kivy.app import App
from kivy.lang import Builder

APP_KV = """
GridLayout:
    cols: 1
    Label:
        id: activity_label
    Button:
        id: activity_button
        text: 'Start'
        on_press: app.activity_toggle()
"""

class MainApp(App):
    def build(self):
        return Builder.load_string(APP_KV)

    def activity_toggle(self):
        if app.root.ids.activity_button.text == 'Start':
            app.root.ids.activity_button.text = 'Stop'
            app.root.ids.activity_label.text = 'Activity Started'
        else:
            app.root.ids.activity_button.text = 'Start'
            app.root.ids.activity_label.text = 'Activity Stopped'            

if __name__ == '__main__':
    app = MainApp()
    app.run()
Related