在KivyMD的MDDropdownMenu中按下标签后如何更改按钮的文本?

时间:2019-08-11 15:33:31

标签: python-3.x kivy

我想知道-在打开MDDropdownMenu后在列表中按一些标签后,如何在Kivy(和KivyMD)中更改按钮的文本。

有我的Main.py

from kivy.app import App
from kivymd.theming import ThemeManager
from kivy.uix.screenmanager import Screen

def toast(text):
    from kivymd.toast.kivytoast import toast

    toast(text)

class MyScreen(Screen):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.menu_items = [
                {
                    "viewclass": "MDMenuItem",
                    "text": "text%d" % i,
                    "callback": self.callback,
                }
                for i in range(1, 3)
            ]

    def change_variable(self, value):
        print("\nvalue=", value)
        self.VARIABLE = value
        print("\tself.VARIABLE=", self.VARIABLE)

    def callback(self, *args):
        toast(args[0])

class MainApp(App):
    title = "KivyMD MDDropdownMenu Demo"
    theme_cls = ThemeManager()

    def build(self):
        return MyScreen()


if __name__ == "__main__":
    MainApp().run()

还有我的Main.kv

#:import MDDropdownMenu kivymd.menus.MDDropdownMenu
#:import MDRaisedButton kivymd.button.MDRaisedButton

<MDMenuItem>:
    on_release: app.root.change_variable(self.text)

<MyScreen>:
    name: 'myscrn'
    MDRaisedButton:
        size_hint: None, None
        size: 3 * dp(48), dp(48)
        text: 'MDButton'
        opposite_colors: True
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}
        on_release: MDDropdownMenu(items=root.menu_items, width_mult=4).open(self)

对不起,英语不好,谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

  1. id赋予主按钮,例如id: mainbutton
  2. text的{​​{1}}事件中更新主按钮的on_release
  3. 可选:将MDMenuItem中的toast(args[0])替换为方法pass中的callback(如果您不想调用toast.py

摘要-kv文件

<MDMenuItem>:
    on_release:
        app.root.ids.mainbutton.text = self.text
        app.root.change_variable(self.text)

<MyScreen>:
    name: 'myscrn'
    MDRaisedButton:
        id: mainbutton
        ...

输出

MDDropdownMenu - before selection MDDropdownMenu - after selection