Kivy, scrollview 自動調節大小 - 图1
© dotmodus

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

Official Document

However, examples from the official document have shown the basics of this widget. But for newbies, it is easy to write an unworking widget due to a lack of understanding of it.

Quick Start

  1. from kivy.uix.gridlayout import GridLayout
  2. from kivy.uix.button import Button
  3. from kivy.uix.scrollview import ScrollView
  4. from kivy.core.window import Window
  5. from kivy.app import runTouchApp
  6. layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
  7. ## Make sure the height is such that there is something to scroll.
  8. layout.bind(minimum_height=layout.setter('height'))
  9. for i in range(100):
  10. btn = Button(text=str(i), size_hint_y=None, height=40)
  11. layout.add_widget(btn)
  12. root = ScrollView(size_hint=(1, None), size=(Window.width, Window.height))
  13. root.add_widget(layout)
  14. runTouchApp(root)

Why Am I failed to scroll my widget

The problem is that after you settled everything in your kv file, the sub-widget has the same size as the ScrollView widget by default. So, to have a functional scrolling behavior, you’d like to make sure the sub-widget is larger than the ScrollView widget. Let’s go back to the example from the document:

  1. ScrollView:
  2. do_scroll_x: False
  3. do_scroll_y: True
  4. Label:
  5. size_hint_y: None
  6. height: self.texture_size[1]
  7. text_size: self.width, None
  8. padding: 10, 10
  9. text:
  10. 'really some amazing text\n' * 100

In this kv file, two lines are important to redefine the height of this sub-widget.

  1. size_hint_y: None
  2. height: self.texture_size[1]

The problem is self.texture_size[1] is for text only. You’d like to replace it with an int, 1000, for example.

But of course, there is a better resolution from @amd, 2015

  1. height: self.minimum_height

An example could show as:

  1. ScrollView:
  2. size: 300, 20
  3. do_scroll_x: False
  4. do_scroll_y: True
  5. BoxLayout:
  6. size_hint_y: None
  7. height: self.minimum_height
  8. padding: 10, 10
  9. MyButton:
  10. text: 'hit me 1'
  11. MyButton:
  12. text: 'hit me 2'
  13. MyButton:
  14. text: 'hit me 3'
  15. MyButton:
  16. text: 'hit me 4'
  17. MyButton:
  18. text: 'hit me 5'
  19. MyButton:
  20. text: 'hit me 6'

Case closed!!!


Enjoy~

本文由Python腳本GitHub/語雀自動更新

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗