📜  Kivy Python ListView Scrollview with Toggle on off - Python (1)

📅  最后修改于: 2023-12-03 14:43:39.987000             🧑  作者: Mango

Kivy Python ListView Scrollview with Toggle on off - Python

Kivy is a framework for building multi-touch and highly-interactive applications. It is written in Python and can run on Windows, Linux, OS X, Android and iOS. In this tutorial, we will be learning how to build a ListView Scrollview with Toggle on off switch using Kivy in Python.

Requirements
  • Python 3.x
  • Kivy
Steps
  1. Import required modules:
from kivy.app import App
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout 
  1. Create a GridLayout:
class Grid(GridLayout):
    def __init__(self, **kwargs):
        super(Grid, self).__init__(**kwargs)
        self.cols = 1
        self.size_hint_y = None
        self.bind(minimum_height=self.setter('height'))
  1. Add toggle buttons to GridLayout:
class Grid(GridLayout):
    def __init__(self, **kwargs):
        super(Grid, self).__init__(**kwargs)
        self.cols = 1
        self.size_hint_y = None
        self.bind(minimum_height=self.setter('height'))
        for i in range(10):
            btn = ToggleButton(text='Button %d'%i, size_hint_y=None, height=40)
            self.add_widget(btn)
  1. Add GridLayout to ScrollView:
class ScrollApp(App):
    def build(self):
        layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        #Make sure the height is such that there is something to scroll.
        layout.bind(minimum_height=layout.setter('height'))
        for i in range(100):
            btn = ToggleButton(text='Button %d' % i, size_hint_y=None, height=40)
            layout.add_widget(btn)
        #Creating Scrollview and adding GridLayout to it.
        root = ScrollView(size_hint=(1, None), size=(800, 800))
        root.add_widget(layout)
        return root

if __name__ == '__main__':
    ScrollApp().run()
Conclusion

We have successfully created a ListView Scrollview with Toggle on off switch using Kivy in Python. This is just an example of what Kivy can do. With Kivy, you can create applications that run on desktop, mobile and web. Kivy is a powerful framework, and I would recommend you to explore it more.