Kivy Popup не может получить доступ к методу root - PullRequest
0 голосов
/ 02 июня 2018

Я новичок здесь, поэтому не стесняйтесь поправлять меня, если я не выполняю надлежащие процедуры.

У меня есть приложение Kivy, которое открывает всплывающее окно.Во всплывающем окне я могу ввести 2 числа, затем нажать кнопку «Добавить», которая должна добавить 2 числа.Я получаю сообщение об ошибке: «AttributeError: объект CustomPopup не имеет атрибута« addNum »»

Почему это так?

test.py file

import kivy
kivy.require('1.9.1') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty

class CustomPopup(Popup):
    pass

class MyStuff(BoxLayout):

    num1 = StringProperty
    num2 = StringProperty
    answer = ''

    def openPopup(self):
        the_popup = CustomPopup()
        the_popup.open()

    def addNum(self):
        self.answer = str(int(self.num1) + int(self.num2))

class MyStuffApp(App):

    def build(self):
        return MyStuff()

if __name__ == '__main__':
    MyStuffApp().run()

mystuff.kv file

#: import main test

<MyStuff>:
    orientation: 'vertical'
    spacing: 5
    padding: 5


    Button:
        text: 'Change numbers'
        on_press: root.openPopup()
        font_size: 50

    Label:
        text: root.answer


<CustomPopup>:
    size_hint: .5, .5
    auto_dismiss: False
    title: 'Addition'
    num1: number2
    num2: number2

    BoxLayout:
        orientation: 'vertical'

        Label:
            text: '1st number'

        TextInput:
            id: number1

        Label
            text: '2nd number'

        TextInput
            id: number2

        Button:
            text: 'Add'
            on_press: root.addNum()

Ответы [ 2 ]

0 голосов
/ 02 июня 2018

Вы можете получить доступ к методам из MyStuff, если у вас есть ссылка где-то на этот класс.
Когда вы делаете root.addNum(), вы пытаетесь получить доступ к методу внутри CustomPopup, который в этом случае является корневым.
Итак, что бы я сделал в этом случае, это определил MyStuff как атрибут вашего App класса (self.ms = MyStuff()).Таким образом, вы можете получить к нему доступ в kv, выполнив app.ms.addNum()
Также вам нужно передать числа в addNum

В py.:

class MyStuff(BoxLayout):

    answer = ''

    def openPopup(self):
        the_popup = CustomPopup()
        the_popup.open()

    def addNum(self, num1, num2):
        self.answer = str(int(num1) + int(num2))

class MyStuffApp(App):

    def build(self):
        self.ms = MyStuff()
        return self.ms

И вкв .::1018*

    Button:
        text: 'Add'
        on_press: app.ms.addNum(number1.text, number2.text)
0 голосов
/ 02 июня 2018

Прежде всего, чтобы получить доступ к addNum, вы должны позвонить app.root.addNum из части kv.Вы также должны отправить значения, которые будут добавлены, то есть текст, который вы ввели в текстовые поля: (number1.text, number2.text).Таким образом, работающий код может выглядеть примерно так:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup

Builder.load_string("""
<MyStuff>:
    orientation: 'vertical'
    spacing: 5
    padding: 5
    Button:
        text: 'Change numbers'
        on_press: root.openPopup()
        font_size: 50

    Label:
        text: root.answer


<CustomPopup>:
    size_hint: .5, .5
    auto_dismiss: False
    title: 'Addition'
    num1: number2
    num2: number2

    BoxLayout:
        orientation: 'vertical'

        Label:
            text: '1st number'

        TextInput:
            id: number1

        Label
            text: '2nd number'

        TextInput
            id: number2

        Button:
            text: 'Add'
            on_press: app.root.addNum(number1.text, number2.text)
""")


class CustomPopup(Popup):
    pass


class MyStuff(BoxLayout):

    # num1 = StringProperty()
    # num2 = StringProperty()
    answer = ''

    def openPopup(self):
        the_popup = CustomPopup()
        the_popup.open()

    def addNum(self, *args):
        # self.answer = str(int(self.num1) + int(self.num2))
        self.answer = str(int(args[0]) + int(args[1]))
        print(self.answer)


class MyStuffApp(App):

    def build(self):
        return MyStuff()


if __name__ == '__main__':
    MyStuffApp().run()
...