Home > Blockchain >  How can i write this construction in py file?
How can i write this construction in py file?

Time:09-15

I want to create many buttons by add_widget function, but i don't know how to make on_release function on py file. Because 'on_release' in py file can't give the argument 'self.text' to function.

MDRoundFlatButton:
    text: "Red"
    on_release: app.theme_cls.primary_palette = self.text

And by the way, how to give a hue to an individual button?

CodePudding user response:

KV:

MDRoundFlatButton:
    text: "Red"
    on_release: app.set_palette(self.text)

Python

def set_palette(self, name_color: str):
    self.theme_cls.primary_palette = name_color

CodePudding user response:

In regards to your second question, use an MDFillRoundFlatButton instead of a MDRoundFlatButton and you can set the md_bg_color property. I've expanded on Xyanight's answer and created a working example:

example.py

from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout

Builder.load_string("""
<MyLayout>:
    size_hint: 0.25, 0.25
    pos_hint: {'center_x': 0.5, 'center_y': 0.5}
    md_bg_color: app.theme_cls.primary_color
    
    MDFillRoundFlatButton:
        text: 'Red'
        md_bg_color: 'red'
        on_release: app.set_palette(self.text)

""")


class MyLayout(MDBoxLayout):
    pass


class MainApp(MDApp):

    def build(self):
        return MyLayout()

    def set_palette(self, name_color: str):
        self.theme_cls.primary_palette = name_color


if __name__ == '__main__':
    app = MainApp()
    app.run()

The KivyMD documentation is a really good resource for referencing all the different widgets available and how to use them.

Here is a the link to the Button page: https://kivymd.readthedocs.io/en/latest/components/button/index.html

  • Related