I'm trying to make a simple cooking app to show step-by-step recipe guide how to make a dish. I'm having problems with creating buttons for every recipe.
I am not familiar with any way how to make a loop in the kivy file, so I tried calling a function from the kivy file when the 'recipes screen' opens. The problem is it only uses the code from the kivy file instead of generating widgets in the function in python file.
Python part:
def build(self):
self.ins = GridLayout()
self.ins.cols = 3
self.ins.add_widget(Label(text="Test"))
Kivy part:
<BakeRecipes>:
name: 'bkrecipes'
on_parent: root.build()
I expected to see the label but I only got a black screen, so I'm assuming it doesn't use he python part as a part of the design. Is there a way to generate buttons inside the kivy file using a loop? Do I need to add something to my code for the program to understand to also generate the python part code alongside kivy code?
Yes, you can generate buttons in Python code and then add them in the widget
py file
class BakeRecipes():
def on_pre_enter(self):
for i in range(0,5): #assuming you need to create 5 buttons
button = Button(text=str(i)) #the text on the button
button.bind(on_press=self.pressed) #when the button is clicked
self.ids.grid.add_widget(button) #added to the grid
kv file
<BakeRecipes>:
name: 'bkrecipes'
GridLayout:
cols:3
id:grid
if you are using Screen
and ScreenManager
then replace class BakeRecipes():
with class BakeRecipes(Screen):
Plus, you would need to write the pressed
function for the buttons
created above. A single function would bind to all the buttons.
Hope this was helpful :)
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.