Search code examples
kivykivy-language

Change text of label does not update text of label KIVY


I am trying to update a text of a label but it does not seem to update the text at all. I have a python file myfirebase.py and a kivy file signinscreen.kv.

The label id is "login_message" that I am trying to update. It is supposed to be updated in the python file with the following command: App.get_running_app().root.ids['signin_screen'] .ids['login_message'].text = 'invalid username or password'

There is no error; but it simply does not update the text of the label.

myfirebase.py:

"""

 import requests
 import json
 from kivy.app import App

 class MyFirebase():

   def sign_in(self, username, password):

       result_users = 
       requests.get("https://uniquedatabase-c4647- 
       default-rtdb.firebaseio.com/" + "users" + ".json")
       data_users = 
                json.loads(result_users.content.decode())

       incorrect_info = True

       for users in data_users.values():
          if username == users['username']:
          passcode = users['password']
               if password == passcode:
                    incorrect_info = False
                    App.get_running_app().my_user_id = 
                                                    users
                    App.get_running_app().change_screen
                                         ('home_screen')
                    break

   if incorrect_info:

        App.get_running_app().root.ids['signin_screen']
        .ids['login_message'].text = 'invalid username or 
        password'

"""

"""

 <SigninScreen>:
     FloatLayout:
          GridLayout:
               rows: 1
               pos_hint: {"top": 1, "right": 1}
               size_hint: 1, .2
               Image:
                    source: 'images/Uniquelogo.jpg'
                    size: self.texture_size
               TextInput:
                    id:login_username
                    hint_text: "username"
                    size_hint: .8,.1
                    pos_hint: {"top": .7, "right": .9}
               TextInput:
                    id:login_password
                    hint_text: "password"
                    size_hint: .8,.1
                    pos_hint: {"top": .5, "right": .9}
               Label:
                    id: login_message
                    text: ''
                    size_hint: .8,.1
                    pos_hint: {"top": .3, "right": .9}
                    color: 1,0,0,1
               Button:
                    pos_hint: {"top": .2, "right": 0.75}
                    size_hint: 0.5, 0.25
                    text: 'Sign In'
                    color: 0,0,0,1
                    background_normal: ''
                    background_color: 1,0.95,0,1
                    on_release:
                     app.my_firebase.sign_in(login_username.text, 
                     login_password.text)

""" Main.py """

        import sys
        sys.path.append("/".join(x for x in __file__.split("/") 
         [:-1]))
        from kivy.app import App
        from kivy.lang import Builder
        from kivy.uix.screenmanager import Screen
        from kivy.uix.button import ButtonBehavior
        from kivy.uix.image import Image
        import requests
        import json
        from myfirebase import MyFirebase
        from workoutbanner import WorkoutBanner
        from kivy.properties import ListProperty, StringProperty, 
        ObjectProperty
        from kivy.utils import platform
        if platform == 'ios':
        from pyobjus import autoclass
        from kivy.clock import mainthread


class HomeScreen(Screen):
      pass

class ImageButton(ButtonBehavior,Image):
      pass

class SigninScreen(Screen):
      pass

class MealofthedayScreen(Screen):
      pass

class SettingsScreen(Screen):
      pass

class SigninScreen(Screen):
      pass

class ColorScreen(Screen):
      pass

class MainApp(App):

     native_image_picker = ObjectProperty(None)
     image_path = StringProperty("")
     my_user_id = "user1"
     user_table = "users"
     activity_table = "activities"
     user_id = StringProperty('user1')
     get_users = requests.get("https://uniquedatabase-c4647-default- 
     rtdb.firebaseio.com/" + user_table + ".json")
     data_get_users = json.loads(get_users.content.decode())
     image_source_profile = 
        StringProperty(str(data_get_users[my_user_id]['picture']))
     color_writings = StringProperty(str(data_get_users[my_user_id] 
                      ['color']))

     def build(self):
       self.my_user_id = 'user1'
       self.my_firebase = MyFirebase()
       GUI = Builder.load_file("main.kv")
       return GUI 

     def on_start(self):
       #Query database data
       if platform == 'ios':
           self.native_image_picker = 
             autoclass("NativeImagePicker").alloc().init()
       result_users = requests.get("https://uniquedatabase-c4647- 
           default-rtdb.firebaseio.com/" + self.user_table + ".json")
       result_activities = requests.get("https://uniquedatabase- 
           c4647-default-rtdb.firebaseio.com/" + self.activity_table 
           + ".json")
       data_users = json.loads(result_users.content.decode())
       data_activities = 
                    json.loads(result_activities.content.decode())
    
       streak_label = 
         self.root.ids['home_screen'].ids['streak_label']
       streak_label.text = str(data_users[self.my_user_id]['streak'])
    
       banner_grid = self.root.ids['home_screen'].ids['banner_grid']
       for workouts in data_activities.values():
             W = 
                WorkoutBanner(user=workouts['user'],
                date=workouts['date'],
                firstName=workouts['firstName']
                ,typeWorkout=workouts['typeOfWorkout'],
                lenghtWorkout=workouts['lenghtOfWorkout']
                ,color_writings = self.color_writings)
             banner_grid.add_widget(W)
        
     def update(self):
          print("Updating image...")

          folder = "/".join(x for x in self.user_data_dir.split("/") 
                  [:-1])
          image_path = folder + "/" + "cached.png"
          self.image_source_profile = image_path
          my_profile_picture_data = '{"picture":"%s"}'%image_path
          requests.patch("https://uniquedatabase-c4647-default- 
            rtdb.firebaseio.com/" + self.user_table + "/" +  
            self.my_user_id + ".json",
                   data=my_profile_picture_data)
        
    def pick_image(self):
         if platform == 'ios':
            self.native_image_picker.displayImagePicker() 
    
    def changeColor(self,color):
        if color == 'red':
            color_code = 'ff0000'
            my_color_data = '{"color":"%s"}'%color_code
             requests.patch("https://uniquedatabase-c4647-default- 
             rtdb.firebaseio.com/" + self.user_table + "/" +  
             self.my_user_id + ".json",
                   data=my_color_data)
        elif color == 'electric blue':
             color_code = '0000ff'
             my_color_data = '{"color":"%s"}'%color_code
            requests.patch("https://uniquedatabase-c4647-default-rtdb.firebaseio.com/" + self.user_table + "/" +  self.my_user_id + ".json",
                   data=my_color_data)
        elif color == 'cyan':
            color_code = '00eeee'
            my_color_data = '{"color":"%s"}'%color_code
            requests.patch("https://uniquedatabase-c4647-default-rtdb.firebaseio.com/" + self.user_table + "/" +  self.my_user_id + ".json",
                   data=my_color_data)
        elif color == 'green':
            color_code = '008000'
            my_color_data = '{"color":"%s"}'%color_code
            requests.patch("https://uniquedatabase-c4647-default-rtdb.firebaseio.com/" + self.user_table + "/" +  self.my_user_id + ".json",
                   data=my_color_data)
        elif color == 'yellow':
            color_code = 'ffff00'
            my_color_data = '{"color":"%s"}'%color_code
            requests.patch("https://uniquedatabase-c4647-default-rtdb.firebaseio.com/" + self.user_table + "/" +  self.my_user_id + ".json",
                   data=my_color_data)
        elif color == 'purple':
            color_code = '9b30ff'
            my_color_data = '{"color":"%s"}'%color_code
            requests.patch("https://uniquedatabase-c4647-default-rtdb.firebaseio.com/" + self.user_table + "/" +  self.my_user_id + ".json",
                   data=my_color_data)
        
    
    #Fill HomeScreen feed
   def change_screen(self,screen_name):
    screen_manager = self.root.ids["screen_manager"]
    screen_manager.current = screen_name

   @mainthread
   def on_correct_info(self, users):
    self.my_user_id = users
    self.change_screen('home_screen')

   @mainthread
   def on_incorrect_info(self):
    self.root.ids['signin_screen'].ids['login_message'].text = 'invalid username or password'
    
MainApp().run()

Solution

  • I think there's an easier way to do this. First of all, I noticed you're not using fstring, I highly recommend using it, in my code example, I've added it there for the requests.get function as an example.

    As well, it seems you can have self.my_firebase = MyFirebase() under the Build function of the app and it should work with the code below

    regarding the id "login_message" - You need to add the label also under SignInScreen, so all other widgets under SigninScreen can access it, finally, I passed login_message in the app.firebase_sigin function, and change its value from there.

    <SigninScreen>
        login_message: login_message
    

    Please take a look, and let me know if you have any further questions:

    myfirebase.py

    from kivy.app import App
    import requests
    import json
    
    
    class MyFirebase():
        BASE_URL = 'https://uniquedatabase-c4647-default-rtdb.firebaseio.com'
    
        def sign_in(self, username, password):
            result_users = requests.get(f"{self.BASE_URL}/users.json")
            data_users = json.loads(result_users.content.decode())
            for users in data_users.values():
                if username == users['username']:
                    passcode = users['password']
                if password == passcode:
                    return True
                else:
                    return False
    

    kv

    <SigninScreen>:
        login_message: login_message
        FloatLayout:
            GridLayout:
                rows: 1
                pos_hint: {"top": 1, "right": 1}
                size_hint: 1, .2
                Label:
                    id: login_message
                    text: ''
                    size_hint: .8,.1
                    pos_hint: {"top": .3, "right": .9}
                    color: 1,0,0,1
                TextInput:
                    id:login_username
                    hint_text: "username"
                    size_hint: .8,.1
                    pos_hint: {"top": .7, "right": .9}
                TextInput:
                    id:login_password
                    hint_text: "password"
                    size_hint: .8,.1
                    pos_hint: {"top": .5, "right": .9}
                Button:
                    pos_hint: {"top": .2, "right": 0.75}
                    size_hint: 0.5, 0.25
                    text: 'Sign In'
                    color: 0,0,0,1
                    on_release:                                        
                        app.firebase_signin(login_username.text, login_password.text, login_message)
    

    main.py

    from kivy.app import App
    from kivy.uix.screenmanager import Screen
    from myfirebase import MyFirebase
    from kivy.lang import Builder
    
    ...    
    
    class SigninScreen(Screen):
        pass
    
    ....
    
    class MainApp(App):
    
        def firebase_signin(self, username, password, login_message):
            succeeded = self.my_firebase.sign_in(username, password)
            if succeeded:
                # here you implement changing screens, etc..
                do_something = "doing something.."
            else:
                login_message.text = "invalid username or password"
    
        def build(self):
            self.my_user_id = 'user1'
            self.my_firebase = MyFirebase()
            GUI = Builder.load_file("main.kv")
            return GUI
    
    
    MainApp().run()
    

    Before pressing the signin button

    Before pressing the signin button

    After pressing the signin button

    After pressing the sigin button