I have creating multiple buttons via for loop in Python/Kivy. I can't figureout how to implement for each button on_press and on_release function, so each button (having it's defined color) will come back to its original color after releasing.
Below You will find part of code in python and kivy.
Python:
class PrButton(GridLayout):
def __init__(self, **kwargs):
super(PrButton, self).__init__(**kwargs)
self.build_grid()
def build_grid(self):
for i in hi_cat():
btn = ButtonDD(text=i[0].upper())
btn.background_color = i[1]
self.ids[i[0]] = btn
self.add_widget(btn)
kivy file:
<ButtonDD>
bold: True
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
KV = """
<MainWidget>:
size : root.size
"""
class MainWidget(BoxLayout):
def __init__(self,**kwargs):
super().__init__(**kwargs)
for i in range(5):
btn = Button(text = str(i))
btn.bind(on_release = lambda i=i:self.clicked(i))
self.add_widget(btn)
def clicked(self,text):
print(text)
class MainApp(MDApp):
def build(self):
Builder.load_string(KV)
return MainWidget()
MainApp().run()
It is achieved by changing lambda x: self.clicked()
To lambda i=i:self.clicked()
I've been stuck with this kind of problem for some time now. But I got my answer recently. So I hope this helps you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.