AttributeError:“healthcareApp”对象没有属性“ids”来通过 tkinter 桌面应用程序从 Firebase 获取数据

问题描述 投票:0回答:1

我想开发 kivy 应用程序,它从 tkinter 应用程序发送的 firebase 实时获取数据。在这里我也使用了 youtube 教程,但我遇到了问题。它是 tkinter 应用程序将数据发送到 firebase,但我无法从 firebase 获取数据并给出错误“AttributeError:'healthcareApp'对象没有属性'ids'”。在 tkinter 应用程序中,标签不显示任何数字,但将生命体征数据发送到 firebase。 我的 tkinter 应用程序代码

import pandas as pd
import tkinter as tk
from tkinter import ttk
import firebase_admin
from firebase_admin import db, credentials
from firebase_admin import firestore

class RealTimeVitalSignsApp:
    def __init__(self, root, excel_file, column_name):
        self.root = root
        self.root.title("Real-Time Vital Signs")

        # Load Excel data
        self.df = pd.read_excel('C:/Users/DELL/PycharmProjects/heart detection thesiswork/training data\data in XLSX format/b_1__p_id_5044545__d_2020_1_10__t_18_35.xlsx')

        cred = credentials.Certificate(
            r"C:/Users/DELL/PycharmProjects/heart detection thesiswork/data-notification-71c1a-firebase-adminsdk-r3e79-8b41638df2.json")
        ###Down line use to connect the firebase database in the python
        #firebase_admin.initialize_app(cred, {"databaseURL": "https://data-notification-71c1a-default-rtdb.firebaseio.com/"})
        firebase_admin.initialize_app(cred)  ##to connect firestore in the python
        self.firestore_db = firestore.client()

        # Create labels to display vital signs
        self.label_heart_rate = ttk.Label(root, text="Heart Rate: ")
        self.label_heart_rate.pack(pady=10)

        self.label_Blood_pressure1 = ttk.Label(root, text="Blood pressure(systolic): ")
        self.label_Blood_pressure1.pack(pady=10)

        self.label_Blood_pressure2 = ttk.Label(root, text="Blood pressure(diastolic): ")
        self.label_Blood_pressure2.pack(pady=10)

        self.label_Saturated_level = ttk.Label(root, text="Saturated level: ")
        self.label_Saturated_level.pack(pady=10)

        self.start_button = ttk.Button(root, text="Start Updating", command=self.update_labels)
        self.start_button.pack(pady=10)

        # Set the initial value
        self.update_index = 0

    def update_labels(self):
        # Check if there are more rows to update
        if self.update_index < len(self.df):
            # Get the value from the DataFrame
            # current_value = self.df.iloc[self.update_index]['HR']

            current_data1= {'HeartRate': int(self.df.iloc[self.update_index]['HR']),}
            current_data2={'Blood pressure(systolic)': float(self.df.iloc[self.update_index]['BP1']),}
            current_data3={'Blood pressure(diastolic)': int(self.df.iloc[self.update_index]['BP2']),}
            current_data4={'Saturated level': int(self.df.iloc[self.update_index]['SPO2']),}
            # Add other fields as needed

            # Update the label
            self.label_heart_rate.config(text=f"HeartRate:{current_data1}")
            self.label_Blood_pressure1.config(text=f"Blood pressure(systolic):{current_data2}")
            self.label_Blood_pressure2.config(text=f"Blood pressure(diastolic): {current_data3}")
            self.label_Saturated_level.config(text=f"Saturated level:{current_data4}")

            # Increment the update index
            self.update_index += 1

            # Categorize the vital sign value
            current_data1['Category'] = self.categorize_vital_signHR(current_data1['HeartRate'])
            current_data2['Category'] = self.categorize_vital_signBP1(current_data2['Blood pressure(systolic)'])
            current_data3['Category'] = self.categorize_vital_signBP2(current_data3['Blood pressure(diastolic)'])
            current_data4['Category'] = self.categorize_vital_signSPO2(current_data4['Saturated level'])

            self.root.after(1000, self.update_labels)

            # Send data to Firebase Cloud Firestore
            self.send_to_firestore(current_data1, current_data2, current_data3, current_data4)

        else:
            # Reset the update index when all rows are processed
            self.update_index = 0

    def categorize_vital_signHR(self, value):
        # Add your conditions to categorize the vital sign value
        if value > 100:
            return "Emergency"
        elif 60 <= value <= 100:
            return "Normal"
        elif value < 60:
            return "Alarming"
        else:
            return "Average"

    def categorize_vital_signBP1(self, value):
        # Add your conditions to categorize the vital sign value
        if value >= 160:
            return "Emergency"
        elif 120 <= value <= 139:
            return "Normal"
        elif 140 <= value <= 159:
            return "Alarming"
        else:
            return "Average"

    def categorize_vital_signBP2(self, value):
        # Add your conditions to categorize the vital sign value
        if value >= 100:
            return "Emergency"
        elif 80 <= value <= 89:
            return "Normal"
        elif 90 <= value <= 99:
            return "Alarming"
        else:
            return "Average"

    def categorize_vital_signSPO2(self, value):
        # Add your conditions to categorize the vital sign value
        if value < 85:
            return "Emergency"
        elif 95 <= value:
            return "Normal"
        elif 94 <= value <= 86:
            return "Alarming"
        else:
            return "Average"

    def send_to_firestore(self, data_dict1, data_dict2, data_dict3, data_dict4):
        # Replace 'patient1' with the actual patient identifier
        patient_id = 'patient1'

        # Replace 'vital_signs' with your desired collection name
        collection_ref = self.firestore_db.collection(patient_id) #.document('vital_signs')

        # Add a new document with all the fields
        # collection_ref.set(data_dict)
        collection_ref.document('HeartRate').set(data_dict1)
        collection_ref.document('BloodPressureSystolic').set(data_dict2)
        collection_ref.document('BloodPressureDiastolic').set(data_dict3)
        collection_ref.document('SaturatedLevel').set(data_dict4)

if __name__ == "__main__":
    # Replace 'your_excel_file.xlsx' with the path to your Excel file
    # Replace 'HeartRate' with the actual column name you want to display
    excel_file_path = 'C:/Users/DELL/PycharmProjects/heart detection thesiswork/training data\data in XLSX format/b_1__p_id_5044545__d_2020_1_10__t_18_35.xlsx'
    column_to_display1 = ['HR', 'BP1', 'BP2', 'SPO2']

    firebase_credential_path = 'C:/Users/DELL/PycharmProjects/heart detection thesiswork/data-notification-71c1a-firebase-adminsdk-r3e79-8b41638df2.json'

    # Create Tkinter root window
    root = tk.Tk()

    # Create the application
    app = RealTimeVitalSignsApp(root, excel_file_path, column_to_display1)

    # Start the Tkinter event loop
    root.mainloop()

########################
# vital_sign_category = self.categorize_vital_sign(current_value)
            # current_value['Category'] = self.categorize_vital_sign(current_value['HeartRate'])
            # Schedule the next update
# self.send_to_firestore(current_data)
            # self.send_to_firestore(current_value,vital_sign_category)
            # self.send_to_firestore(current_data1)
            # self.send_to_firestore(current_data2)
            # self.send_to_firestore(current_data3)
            # self.send_to_firestore(current_data4)
########################
# # heart_rate = int(heart_rate)
        # #collection_ref = self.firestore_db.collection('patient 1').document('heartrate')
        # heart_rate = int(heart_rate)
        # Blood_pressure1 = float(Blood_pressure1)
        # Blood_pressure2 = int(Blood_pressure2)
        # Saturated_level = int(Saturated_level)
        #
        # patient_id = 'patient1'
        #
        # # Replace 'heartrate' with your desired collection name
        # # collection_ref = self.firestore_db.collection(patient_id).document('heartrate')
        # collection_ref1 = self.firestore_db.collection(patient_id).document('Heart_Rate')
        # collection_ref2 = self.firestore_db.collection(patient_id).document('Blood_pressure1')
        # collection_ref3 = self.firestore_db.collection(patient_id).document('Blood_pressure2')
        # collection_ref4 = self.firestore_db.collection(patient_id).document('Saturated_level')
        #
        # # Add a new document with the heart rate and category as fields
        # document_data1 = {'Heart Rate': heart_rate, 'Category': category}
        # document_data2 = {'Blood pressure 1': Blood_pressure1, 'Category': category}
        # document_data3 = {'Blood pressure 2': Blood_pressure2, 'Category': category}
        # document_data4 = {'Saturated level': Saturated_level, 'Category': category}
        #
        # # collection_ref.set(document_data)
        # collection_ref1.set(document_data1)
        # collection_ref2.set(document_data2)
        # collection_ref3.set(document_data3)
        # collection_ref4.set(document_data4)

我的 kivy 应用程序代码如下:

from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.screen import Screen
from kivymd.uix.button import MDFlatButton, MDRectangleFlatButton, MDIconButton, MDFloatingActionButton
from kivymd.uix.dialog import MDDialog
from kivymd.uix.textfield import MDTextField
from kivymd.uix.list import MDList, OneLineListItem, TwoLineListItem, ThreeLineListItem
from kivymd.uix.list import IconLeftWidget, TwoLineIconListItem
from kivy.uix.scrollview import ScrollView
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivymd.uix.datatables import MDDataTable
from kivy.metrics import dp
from kivy.core.window import Window
from firebase_admin import credentials, firestore, initialize_app
from kivy.clock import Clock

# from kivymd.uix.toolbar import MDTopAppBar

Window.size = (300, 500)

screen_helper = """
ScreenManager:
    MenuScreen:
    PatientOne:
    PatientTwo:
    PatientThree:
    PatientFour:
    PatientFive:
    PatientSix:
    PatientSeven:
    PatientEight:
    PatientNine:
    PatientTen:
           
<MenuScreen>:
    name:'menu'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Home Screen'
            elevation: 5
        Widget:
           
    MDRectangleFlatButton:
        text:'b_1'
        pos_hint: {'center_x':0.2,'center_y':0.1}
        on_press:
            root.manager.current = 'patient1'
            root.manager.transition.direction = 'left'
            
    MDRectangleFlatButton:
        text:'b_2'
        pos_hint: {'center_x':0.2,'center_y':0.2}
        on_press:
            root.manager.current = 'patient2'
            root.manager.transition.direction = 'left'
            
    MDRectangleFlatButton:
        text:'b_3'
        pos_hint: {'center_x':0.2,'center_y':0.3}
        on_press:
            root.manager.current = 'patient3'
            root.manager.transition.direction = 'left'
            
    MDRectangleFlatButton:
        text:'b_4'
        pos_hint: {'center_x':0.2,'center_y':0.4}
        on_press:
            root.manager.current = 'patient4'
            root.manager.transition.direction = 'left'
            
    MDRectangleFlatButton:
        text:'b_5'
        pos_hint: {'center_x':0.2,'center_y':0.5}
        on_press:
            root.manager.current = 'patient5'
            root.manager.transition.direction = 'left'
    
    MDRectangleFlatButton:
        text:'b_6'
        pos_hint: {'center_x':0.6,'center_y':0.1}
        on_press:
            root.manager.current = 'patient6'
            root.manager.transition.direction = 'left'
            
    MDRectangleFlatButton:
        text:'b_7'
        pos_hint: {'center_x':0.6,'center_y':0.2}
        on_press:
            root.manager.current = 'patient7'
            root.manager.transition.direction = 'left'
            
    MDRectangleFlatButton:
        text:'b_8'
        pos_hint: {'center_x':0.6,'center_y':0.3}
        on_press:
            root.manager.current = 'patient8'
            root.manager.transition.direction = 'left'
            
    MDRectangleFlatButton:
        text:'b_9'
        pos_hint: {'center_x':0.6,'center_y':0.4}
        on_press:
            root.manager.current = 'patient9'
            root.manager.transition.direction = 'left'
            
    MDRectangleFlatButton:
        text:'b_10'
        pos_hint: {'center_x':0.6,'center_y':0.5}
        on_press:
            root.manager.current = 'patient10'
            root.manager.transition.direction = 'left'
  

<PatientOne>:
    name:'patient1'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 1'
            elevation: 5
        Widget:
    MDLabel:
        id: heart_rate_label
        text: "Heart Rate: "   
        pos_hint: {'center_x':0.6,'center_y':0.7} 
           
    MDLabel:
        id: blood_pressure1_label
        text: "Blood Pressure (Systolic): "
        pos_hint: {'center_x':0.6,'center_y':0.6} 
    
    MDLabel:
        id: blood_pressure2_label
        text: "Blood Pressure (Diastolic): "
        pos_hint: {'center_x':0.6,'center_y':0.5} 
        
    MDLabel:
        id: saturated_level_label
        text: "Saturated Level: "
        pos_hint: {'center_x':0.6,'center_y':0.4}
        
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.1}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'
          
<PatientTwo>:
    name:'patient2'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 2'
            elevation: 5
        Widget:
            
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.5}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'
            
<PatientThree>:
    name:'patient3'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 3'
            elevation: 5
        Widget:
            
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.5}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'
            
<PatientFour>:
    name:'patient4'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 4'
            elevation: 5
        Widget:
            
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.5}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'
            
<PatientFive>:
    name:'patient5'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 5'
            elevation: 5
        Widget:
            
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.5}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'
            
<PatientSix>:
    name:'patient6'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 6'
            elevation: 5
        Widget:
            
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.5}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'
            
<PatientSeven>:
    name:'patient7'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 7'
            elevation: 5
        Widget:
            
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.5}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'
            
<PatientEight>:
    name:'patient8'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 8'
            elevation: 5
        Widget:
            
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.5}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'
            
<PatientNine>:
    name:'patient9'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 9'
            elevation: 5
        Widget:
            
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.5}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'
                        
<PatientTen>:
    name:'patient10'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 10'
            elevation: 5
        Widget:
            
    MDRectangleFlatButton:
        text:'Back to Menu'
        pos_hint: {'center_x':0.5,'center_y':0.5}
        on_press:
            root.manager.current = 'menu'
            root.manager.transition.direction = 'right'

"""

class MenuScreen(Screen):
    pass


class PatientOne(Screen):
    pass

class PatientTwo(Screen):
    pass

class PatientThree(Screen):
    pass

class PatientFour(Screen):
    pass

class PatientFive(Screen):
    pass

class PatientSix(Screen):
    pass

class PatientSeven(Screen):
    pass

class PatientEight(Screen):
    pass

class PatientNine(Screen):
    pass

class PatientTen(Screen):
    pass




sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(PatientOne(name='patient1'))
sm.add_widget(PatientTwo(name='patient2'))
sm.add_widget(PatientThree(name='patient3'))
sm.add_widget(PatientFour(name='patient4'))
sm.add_widget(PatientFive(name='patient5'))
sm.add_widget(PatientSix(name='patient6'))
sm.add_widget(PatientSeven(name='patient7'))
sm.add_widget(PatientEight(name='patient8'))
sm.add_widget(PatientNine(name='patient9'))
sm.add_widget(PatientTen(name='patient10'))


class healthcareApp(MDApp):

    def __init__(self, **kwargs):
        super(healthcareApp, self).__init__(**kwargs)

        # Initialize Firebase
        cred = credentials.Certificate(r"C:/Users/DELL/PycharmProjects/heart detection thesiswork/data-notification-71c1a-firebase-adminsdk-r3e79-8b41638df2.json")
        initialize_app(cred)
        self.firestore_db = firestore.client()
        Clock.schedule_interval(self.update_labels, 1)

    def update_labels(self, dt):
        # Reference to the Firebase Firestore collection
        collection_ref = self.firestore_db.collection('patient1').document('vitals')

        # Retrieve the document data
        doc = collection_ref.get().to_dict()

        # Update the labels with real-time data
        if doc:
            self.ids.heart_rate_label.text = f"Heart Rate: {doc.get('HeartRate', '')}"
            self.ids.blood_pressure1_label.text = f"Blood Pressure (Systolic): {doc.get('BloodPressureSystolic', '')}"
            self.ids.blood_pressure2_label.text = f"Blood Pressure (Diastolic): {doc.get('BloodPressureDiastolic', '')}"
            self.ids.saturated_level_label.text = f"Saturated Level: {doc.get('SaturatedLevel', '')}"

    def build(self):
        self.theme_cls.primary_palette = 'Red'
        self.theme_cls.material_style = "M2"
        screen = Builder.load_string(screen_helper)
        return screen

    def navigation_draw(self):
        print("Navigation")


healthcareApp().run()

[输入图像描述他在此处输入图像描述re](https://i.sstatic.net/FyAR36TV.png) 在此输入图片描述

python firebase-realtime-database mobile kivy kivymd
1个回答
0
投票

定义的

ids
仅存在于定义它们的规则的
ids
字典中。它们从来不在
App
本身之中。例如代码:

<PatientOne>:
    name:'patient1'
    BoxLayout:
        orientation: 'vertical'
        MDTopAppBar:
            title: 'Patient 1'
            elevation: 5
        Widget:
    MDLabel:
        id: heart_rate_label

heart_rate_label
id
的规则内定义
PatientOne
Screen
。这样
id
只会出现在
ids
实例的
PatientOne
字典中。

要访问

heart_rate_label
id
,您可以遍历
App
的小部件树向下到
PatientOne
Screen
。尝试更换:

self.ids.heart_rate_label.text = f"Heart Rate: {doc.get('HeartRate', '')}"

与:

self.root.get_screen('PatientOne').ids.heart_rate_label.text = f"Heart Rate: {doc.get('HeartRate', '')}"
© www.soinside.com 2019 - 2024. All rights reserved.