Как восстановить TextInput с одного экрана на другом в Kivy / Python? - PullRequest
0 голосов
/ 03 сентября 2018

Я пытаюсь сделать приложение, которое может рассчитать объем конуса (пока). У меня есть экран с именем ConeVolumeScreen, который имеет два виджета TextInput.

<ConeVolumeScreen>:
    BoxLayout:
        orientation: ...
        padding: ...
        spacing: ...
        Label:
            text: 'Radius:'
        TextInput:
            id: cone_vol_radius
            multiline: False
            input_type: 'number'
        Label:
            text: 'Height:'
        TextInput:
            id: cone_vol_height
            multiline: False
            input_type: 'number'
        Button:
            text: 'Solve'
            on_release: app.root.changeScreen('solve cone volume')               

Человек должен ввести радиус и высоту конуса в эти два виджета. Затем человек может нажать на кнопку, чтобы перейти к следующему экрану с именем SolveConeVolumeScreen. На этом экране есть Метка, которая должна напечатать объем конуса, который указал человек.

<SolveConeVolumeScreen>:
    BoxLayout:
        orientation: ...
        padding: ...
        spacing: ...
        Label:
            text: app.getConeVolume(cone_vol_radius, cone_vol_height)

getConeVolume () - это метод здесь

class CalculatorRoot(BoxLayout):
    def __init__(self, **kwargs):
        super(CalculatorRoot, self).__init__(**kwargs)
        self.screen_list = []

    def changeScreen(self, next_screen):
        if self.ids.calc_screen_manager.current not in self.screen_list:
            self.screen_list.append(self.ids.calc_screen_manager.current)

        if next_screen == 'volume':
            self.ids.calc_screen_manager.current = 'volume_screen'
        elif next_screen == 'area_screen':
            self.ids.calc_screen_manager.current = 'area_screen'
        elif next_screen == 'surface area':
            self.ids.calc_screen_manager.current = 'surfarea_screen'
        elif next_screen == 'cone volume':
            self.ids.calc_screen_manager.current = 'coneVolume_screen'
        elif next_screen == 'solve cone volume':
            self.ids.calc_screen_manager.current = 'solveConeVolume_screen'
        elif next_screen == 'rectangular based pyramid volume':
            self.ids.calc_screen_manager.current = 'rectPyramidVolume_screen'

    def onBackButton(self):
        if self.screen_list:
            self.ids.calc_screen_manager.current = self.screen_list.pop()
            return True
        return False



class CalculatorApp(App):
    def __init__(self, **kwargs):
        super(CalculatorApp, self).__init__(**kwargs)
        Window.bind(on_keyboard=self.onBackButton)

    def onBackButton(self, window, key, *args):
        if key == 27:
            return self.root.onBackButton()

    def build(self):
        return CalculatorRoot()

    def getConeVolume(self, r, h):
        first_step = 'π * ' + str(r) + '^2 * ' + str(h) + ' / 3\n'
        rr = round(r * r, 2)
        second_step = 'π * ' + str(rr) + ' * ' + str(h) + ' / 3\n'
        rh = round(rr * h, 2)
        third_step = 'π * ' + str(rh) + ' / 3\n'
        pirh = round(pi * rh, 2)
        fourth_step = str(pirh) + ' / 3\n'
        result = round(pi * rh, 2)
        final_step = 'The answer is ' + str(result) + '.'
        thing = first_step + second_step + third_step + fourth_step + final_step
        return thing

Но ошибка говорит о том, что cone_vol_radius не определен.

 ...
 128:        spacing: min(root.width, root.height) * .02
 129:        Label:

130: текст: app.getConeVolume (cone_vol_radius, cone_vol_height) 131: 132 :: ... BuilderException: Parser: File "/ Users / fayzulloh / Desktop / Calculator App / calculator.kv", строка 130: ... 128: интервал: мин. (Root.width, root.height) * .02 129: ярлык: 130: текст: app.getConeVolume (cone_vol_radius, cone_vol_height) 131: 132 :: ... NameError: имя 'cone_vol_radius' не определено

пожалуйста, помогите. Буду очень признателен за любой совет.

вот мой экранный менеджер

<CalculatorRoot>:
    orientation: "vertical"

    ScreenManager:
        id: calc_screen_manager
        StartScreen:
            name: 'start_screen'
        VolumeScreen:
            id: volume_screen
            name: 'volume_screen'
        AreaScreen:
            id: area_screen
            name: 'area_screen'
        SurfaceAreaScreen:
            id: surfarea_screen
            name: 'surfarea_screen'
        ConeVolumeScreen:
            id: coneVolume_screen
            name: 'coneVolume_screen'
        SolveConeVolumeScreen:
            id: solveConeVolume_screen
            name: 'solveConeVolume_screen'
        RectPyramidVolumeScreen:
            id: rectPyramidVolume_screen
            name: 'rectPyramidVolume_screen'

1 Ответ

0 голосов
/ 03 сентября 2018

Ошибка

В приложении есть несколько ошибок.

NameError - Решение

Добавить root.ids.ids.coneVolume_screen.ids. к аргументам.

AttributeError

После решения NameError произойдет AttributeError. AttributeError: 'NoneType' object has no attribute 'ids'. Это потому, что внутренние идентификаторы еще не доступны.

Kivy Language »идентификаторы

Обратите внимание , что самый внешний виджет применяет правила kv ко всем своим внутренним виджетам перед применением любых других правил. Это означает, что если внутренний виджет содержит идентификаторы, эти идентификаторы могут быть недоступны во время Функция __init__ внутреннего виджета.

AttributeError: идентификаторы - Решения

  1. Дайте id метке, например. id: result
  2. Добавить событие on_pre_enter для вызова метода getConeVolume().
  3. Замените объект TextInput текстом TextInput, т.е. замените cone_vol_radius и cone_vol_height на cone_vol_radius.text и cone_vol_height.text соответственно.
  4. Добавление int() функции для преобразования текста / строки TextInput в целое число.

Сниппет

<SolveConeVolumeScreen>:
    on_pre_enter:
        root.ids.result.text = app.getConeVolume(int(app.root.ids.coneVolume_screen.ids.cone_vol_radius.text), int(app.root.ids.coneVolume_screen.ids.cone_vol_height.text))

    BoxLayout:
        orientation: 'vertical'
        Label:
            id: result

выход

Img01 - ConeVolume Screen Img02 - SolveConeVolume Screen

...