更改标签文本不会更新标签 KIVY 的文本

Change text of label does not update text of label KIVY

我正在尝试更新标签的文本,但它似乎根本没有更新文本。我有一个 python 文件 myfirebase.py 和一个 kivy 文件 signinscreen.kv.

我正在尝试更新的标签 ID 是“login_message”。它应该使用以下命令在 python 文件中更新:App.get_running_app().root.ids['signin_screen'] .ids['login_message'].text = 'invalid username or password'

没有错误;但它根本不会更新标签的文本。

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()

我认为有一种更简单的方法可以做到这一点。 首先,我注意到您没有使用 fstring,我强烈建议您使用它,在我的代码示例中,我已将其添加到 requests.get 函数中作为示例。

此外,您似乎可以在应用程序的 Build 功能下使用 self.my_firebase = MyFirebase(),它应该可以使用下面的代码

关于 ID“login_message” - 您还需要在 SignInScreen 下添加标签,以便 SigninScreen 下的所有其他小部件都可以访问它,最后,我在 [=50] 中传递了 login_message =] 函数,并从那里更改它的值。

<SigninScreen>
    login_message: login_message

请看一下,如果您还有其他问题,请告诉我:

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()

在按下登录按钮之前

按下登录按钮后