如何更新kivy的对话框文本

how to update kivy's dialog text

我想根据变量的值更改对话框文本,但是对话框文本没有更新..

我的代码:

from kivy.lang import Builder

from kivymd.app import MDApp
from kivymd.uix.button import MDFlatButton
from kivymd.uix.dialog import MDDialog

KV = '''
MDFloatLayout:

    MDFlatButton:
        text: "ALERT DIALOG"
        pos_hint: {'center_x': .5, 'center_y': .5}
        on_release: app.show_alert_dialog()
'''


class Example(MDApp):
    dialog = None
    var1="var1 value is 10"

    def build(self):
        return Builder.load_string(KV)
        

    def show_alert_dialog(self):
        if not self.dialog:
            self.dialog = MDDialog(
                text=self.var1,
                buttons=[
                    MDFlatButton(
                        text="CANCEL", text_color=self.theme_cls.primary_color
                    ),
                    MDFlatButton(
                        text="DISCARD", text_color=self.theme_cls.primary_color,on_release= self.dialog_close
                    ),
                ],
            )
        self.dialog.open()

    def dialog_close(self, *args):
        self.dialog.dismiss(force=True)
        print(self.var1)
        self.var1="var1 value is 30"

Example().run()

在我的控制台上,变量更改了值,但对话框继续使用以前的值。

var1 没有链接到文本值,您只是复制了 var 的值,而不是引用,所以当您更改 var 时,它不会更改您的文本。以下是更改文本的方法。

from kivy.lang import Builder

from kivymd.app import MDApp
from kivymd.uix.button import MDFlatButton
from kivymd.uix.dialog import MDDialog

KV = '''
MDFloatLayout:

    MDFlatButton:
        text: "ALERT DIALOG"
        pos_hint: {'center_x': .5, 'center_y': .5}
        on_release: app.show_alert_dialog()
'''


class Example(MDApp):
    dialog = None
    var1 = "var1 value is 10"

    def build(self):
        return Builder.load_string(KV)

    def show_alert_dialog(self):
        if not self.dialog:
            self.dialog = MDDialog(
                text=self.var1,
                buttons=[
                    MDFlatButton(
                        text="CANCEL", text_color=self.theme_cls.primary_color
                    ),
                    MDFlatButton(
                        text="DISCARD", text_color=self.theme_cls.primary_color, on_release=self.dialog_close
                    ),
                ],
            )
        self.dialog.open()

    def dialog_close(self, *args):
        self.dialog.dismiss(force=True)
        print(self.var1)
        self.var1 = "var1 value is 30"
        self.dialog.text = self.var1


Example().run()