Search code examples
pythonkivypopupkivy-language

How to open a popup with an argument


I am trying to open a popup-message with a specific argument (errortype) to define in the popup-kv which text schould be shown.

I've tried it with a seperat class (ErrorPopUp) but i am not able to call the popup-method with the argument.

"'ErrorPopup' object has no attribute 'errortype'"

This should be a reproducible example.

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty


class MainWindow(Screen):

    float_weight = ObjectProperty(None)

    def btn(self):
        try:
            float_weight = float(self.float_weight.text.replace(',', '.'))
        except:
            ErrorPopup().ErrorMessage('errorweight')

class ErrorPopup(Popup):
    kv = Builder.load_file("error.kv")
    def ErrorMessage(self, errortype):
        Popup.open(self)


class WindowManager(ScreenManager):
    pass


class MyMainApp(App):
    def build(self):
        return kv


if __name__ == '__main__':
    kv = Builder.load_file("my.kv")
    MyMainApp().run()

my.kv:

WindowManager:
    MainWindow:

<MainWindow>:
    name: "main"

    float_weight: float_weight

    GridLayout:
        cols:1

        GridLayout:
            cols:2

            Label:
                text: "Gewicht:"

            TextInput:
                id: float_weight
                multiline: False

        Button:
            text: "Test3"
            on_press:root.btn()

error.kv:

<ErrorPopup>:
    title: 'Fehlerhafte Eingabe'
    size_hint: (None, None)
    size: (400, 400)
    Label:
        text: root.errortype

Solution

  • In your error.kv, you ran text: root.errortype. What kivy understands is that there is a variable in the ErrorPopup class, but returns an error because it simply does not exist. The variable is within the function ErrorMessage() which is inaccessible unless you return it, which is not what you want. My suggestion for your .py and error.kv files are:

    .py

    class ErrorPopup(Popup):
        kv = Builder.load_file("error.kv")
        def ErrorMessage(self, errortype):
            self.ids.LABEL.text = errortype
            Popup.open(self)
    

    error.kv

    <ErrorPopup>:
        title: 'Fehlerhafte Eingabe'
        size_hint: (None, None)
        size: (400, 400)
        Label:
            id: LABEL
            text: ''
    

    It worked perfectly fine with me, should work with you too!