How do I add buttons that are dynamically created in pure python to a kivy layout that is Written in Kivy Language?

后端 未结 1 1099
故里飘歌
故里飘歌 2021-02-10 08:29

My problem is that I need to create a grid of buttons based on a variable number of grid squares, and place them on a grid layout and display them on a screen using the screen m

1条回答
  •  野性不改
    2021-02-10 09:33

    I hope this example makes it clear for you:

    test.kv:

    #:kivy 1.9.0
    ScreenManager:
        MapScreen:
    
    :
        name: 'map'
    
        GridLayout:
            id: grid
            cols: 1
    

    main.py:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    from kivy.app import App
    from kivy.uix.screenmanager import Screen
    from kivy.uix.button import Button
    from kivy.clock import mainthread
    
    NUMBER_OF_BUTTONS = 5
    
    
    class MapScreen(Screen):
    
        @mainthread
        def on_enter(self):
            for i in xrange(NUMBER_OF_BUTTONS):
                button = Button(text="B_" + str(i))
                self.ids.grid.add_widget(button)
    
    
    class Test(App):
        pass
    
    
    Test().run()
    

    The @mainthead decorator is needed to slightly delay the function, so the kv file gets scanned first, making the ids list viable.

    0 讨论(0)
提交回复
热议问题