Пытаюсь изо всех сил понять это: AttributeError: у объекта 'NoneType' нет атрибута 'text' - PullRequest
0 голосов
/ 25 февраля 2020

Я знаю, что это, вероятно, простой ответ, и я копался в попытках выяснить это, но, похоже, не могу этого понять. Каждый раз, когда я запускаю это, когда я нажимаю кнопку, чтобы вызвать метод, у меня всегда возникает одна и та же проблема. Я стараюсь изо всех сил, чтобы понять эту штуку, но сейчас она становится лучше меня.

AttributeError: у объекта 'NoneType' нет атрибута 'text'

import kivymd
from kivy.app import App
from kivymd.app import MDApp
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.textfield import MDTextField
from kivy.properties import ObjectProperty


class MainApp(MDApp):

    height_feet = ObjectProperty(None)
    height_feet = height_feet
    height_inches = ObjectProperty(None)
    weight = ObjectProperty(None)
    bmiout = ObjectProperty(None)


    def calculate(self):
        height_feet = float(self.height_feet.text)
        height_feet = float(height_feet * 12)
        height_inches = float(self.height_inches.text)
        height = float(height_feet + height_inches)
        weight = float(self.weight.text)
        bmi = int(weight / (height * height) * 703)
        percent = str("%")
        self.bmiout.text = "{}{}".format(bmi, percent)
        self.height_feet.text = ""
        self.height_inches.text = ""
        self.weight.text = ""


    def __init__(self, **kwargs):
        self.title = "BMI"
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Blue"
        super().__init__(**kwargs)



MainApp().run()

'KV'

#:import MDTextField kivymd.uix.textfield.MDTextField
#:import MDFillRoundFlatIconButton kivymd.uix.button.MDFillRoundFlatIconButton


BoxLayout:
    id:layout
    size_hint: .8, .8
    pos_hint: {"center_x": .5, "center_y": .5}
    spacing: dp(50)
    orientation: 'vertical'

    height_feet: height_feet
    height_inches: height_inches
    weight: weight
    bmiout: bmiout

    Label:
        text: "BMI"
        font_size: 100

    MDTextField:
        id: height_feet
        hint_text: "Enter your height in feet"
        require: True
        max_text_length: 1
        halign: 'center'


    MDTextField:
        id: height_inches
        hint_text: "Enter your height in inches"
        require: True
        max_text_length: 2
        halign: "center"

    MDTextField:
        id: weight
        hint_text: "Enter your weight"
        require: True
        max_text_length: 3
        halign: "center"


    Label:
        text: "Your BMI is"
        font_size: 60

    Label:
        id: bmiout
        font_size: 60

    MDFillRoundFlatIconButton:
        text: "Calculate"
        icon: "calculator"
        pos_hint:{ "center_x": .5, "center_y": .5}
        width: dp(25)
        on_release:
            app.calculate()

1 Ответ

0 голосов
/ 25 февраля 2020

Ну, вы должны связать свойства вашего объекта с виджетами. Пока это не сделано, это None.

from kivy.clock import Clock
...
class MainApp(MDApp):

    # isn't it more readable when init is at the start?
    def __init__(self, **kwargs):
        self.title = "BMI"
        # run function with delay
        Clock.schedule_once(self.connectwidgets)
        super().__init__(**kwargs)

    # KivyMD can break when theme manager is in the init method
    # so I put it here, just in case
    theme_cls.theme_style = "Dark"
    theme_cls.primary_palette = "Blue"

    height_feet = ObjectProperty(None)
    height_inches = ObjectProperty(None)
    weight = ObjectProperty(None)
    bmiout = ObjectProperty(None)

    # As I said you should connect properties with widgets with using it's IDs
    # but we have to delay running this function because instead Kivy run it before getting the widgets from kv file and won't work. Again.
    def connectwidgets(self, *args):
        self.height_feet = self.ids.height_feet
        self.height_inches = self.ids.height_inches
        self.weight = self.ids.weight
        self.bmiout = self.ids.bmiout

    def calculate(self):
        height_feet = float(self.height_feet.text)
        height_feet = float(height_feet * 12)
        height_inches = float(self.height_inches.text)
        height = float(height_feet + height_inches)
        weight = float(self.weight.text)
        bmi = int(weight / (height * height) * 703)
        percent = str("%")
        self.bmiout.text = "{}{}".format(bmi, percent)
        self.height_feet.text = ""
        self.height_inches.text = ""
        self.weight.text = ""

MainApp().run()

PS. Я не знаю, работает ли это, потому что я никогда не помещал виджеты в класс App, но попробую.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...