In this Python Kivy article we want to learn about How to Create ScrollView in Python Kivy, when you are building GUI applications with Python and Kivy. some times you will need to display scrollable view for large amount of content, so ScrollView in Kivy allows you to do just that. in this article i want to show you how to create a ScrollView in Python Kivy.
The first thing is this that we need to install Python Kivy, and we can use pip for the installation.
1 |
pip install kivy |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
from kivy.app import App from kivy.uix.scrollview import ScrollView from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label class ScrollViewApp(App): def build(self): scroll_view = ScrollView(size_hint=(0.8, 0.8), size=(400, 400)) # Create container widget container = BoxLayout(orientation='vertical', size_hint_y=None) # Set height of the container widget to # match the number of labels container.bind(minimum_height=container.setter('height')) # Add content to the container widget for i in range(50): label = Label(text=f"GeeksCoders {i}", size_hint=(1, None), height=30) container.add_widget(label) # Add container widget to the ScrollView scroll_view.add_widget(container) return scroll_view ScrollViewApp().run() |
In the above code these are our imports
1 2 3 4 |
from kivy.app import App from kivy.uix.scrollview import ScrollView from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label |
This code creates ScrollView, size_hint property of the ScrollView is set to (0.8, 0.8), which means that the widget should take up 80% of the available space in both the horizontal and vertical directions. size property of the ScrollView is set to (400, 400), which means that the widget should have a fixed size of 400 pixels in both the horizontal and vertical directions.
1 |
scroll_view = ScrollView(size_hint=(0.8, 0.8), size=(400, 400)) |
Now that we have our ScrollView widget, we need to add content to it. in Kivy, you can add widgets to a ScrollView using add_widget method. this is an example:
1 2 3 4 |
for i in range(50): label = Label(text=f"GeeksCoders {i}", size_hint=(1, None), height=30) container.add_widget(label) scroll_view.add_widget(container) |
Run the complete code and this will be the result
