简体   繁体   English

有没有办法在猕猴桃中生成多个按钮?

[英]Is there a way to generate multiple buttons in kivy?

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. 我不熟悉如何在kivy文件中进行循环,因此我尝试在“配方屏幕”打开时从kivy文件中调用函数。 The problem is it only uses the code from the kivy file instead of generating widgets in the function in python file. 问题在于它仅使用kivy文件中的代码,而不是在python文件中的函数中生成小部件。

Python part: Python部分:

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. 我希望看到标签,但是我只有一个黑屏,所以我假设它不使用他的python零件作为设计的一部分。 Is there a way to generate buttons inside the kivy file using a loop? 有没有一种方法可以使用循环在kivy文件中生成按钮? Do I need to add something to my code for the program to understand to also generate the python part code alongside kivy code? 我是否需要在代码中添加一些内容,以便程序理解,以便与kivy代码一起生成python部件代码?

Yes, you can generate buttons in Python code and then add them in the widget 是的,您可以使用Python代码生成按钮,然后将其添加到小部件中

py file py文件

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 KV文件

<BakeRecipes>:
    name: 'bkrecipes'
    GridLayout:
        cols:3
        id:grid

if you are using Screen and ScreenManager then replace class BakeRecipes(): with class BakeRecipes(Screen): 如果使用的是ScreenScreenManager则将class BakeRecipes(): class BakeRecipes(Screen):

Plus, you would need to write the pressed function for the buttons created above. 另外,您需要为上面创建的buttons编写pressed功能。 A single function would bind to all the buttons. 单个功能将绑定到所有按钮。

Hope this was helpful :) 希望这对您有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM