简体   繁体   中英

How to 'Update' dynamically created buttons on a screen in Kivy

I am creating a 'drink menu' that is populated by dynamically creating a button for each possible drink that you could make with the given inputs on this screen. I have two problems with this code, I need to be able to update the drinks available if they change, so I must clear the buttons and re-create them. I am thinking I could clear them every time the page is opened and repopulate. When I try to run this code it just clears the widgets but doesn't repopulate it with the new ones, anyone know a better way or what I'm doing wrong?

class DrinksMenu(Screen):

    @mainthread
    #need to make it so drink menu updates with update button, need to clear widgets somehow and refresh drink list and add new ones
    def on_enter(self):
        db.build_drink_menu()
        self.clear_widgets()
        self.ids.grid.add_widget(Button(text="Main Menu",on_press=self.mainmen))
        for drink in db.drinkmenu:
            button = Button(text=str(drink.get("name")), on_press=partial(drink_select, str(drink.get("name"))))
            self.ids.grid.add_widget(button)
    def mainmen(self):
        sm.current = "mainmenu"

.kv file

<DrinksMenu>:
    name: "drinksmenu"

    GridLayout:
        id:  grid
        cols: 1

If you clear all the widgets in DrinksMenu , then the grid will no longer be in the DrinksMenu , so your new Buttons will be in a GridLayout that is no longer in your GUI. Try changing:

self.clear_widgets()

to:

self.ids.grid.clear_widgets()

to just remove the Buttons that are in the GridLayout .

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.

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