You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy遇帧前迭代过多错误,求实现100个按钮组成的滚动条

解决Kivy中"too much iteration done before the next frame"错误并实现100个按钮的滚动布局

错误原因

在__init__方法中一次性创建并添加大量控件(比如100个按钮)会阻塞UI主线程,导致Kivy无法及时完成帧渲染,触发该错误。

解决方案

通过分批异步添加控件的方式,让UI线程有时间处理帧更新。使用Kivy的Clock调度器,分批次创建并添加按钮,避免一次性占用过多主线程资源。

修改后的完整代码

from kivy.app import App
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.lang import Builder
from kivy.clock import Clock

Builder.load_string('''
<ScrollViewExample@ScrollView>:
    StackLayoutExample:
        size_hint: 1, None
        height: self.minimum_height
''')

class StackLayoutExample(StackLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.current_btn_count = 0
        # 调度分批添加按钮,0表示尽快执行但不阻塞帧渲染
        Clock.schedule_interval(self.add_batch_buttons, 0)

    def add_batch_buttons(self, dt):
        # 每次添加10个按钮,直到总数达到100
        for _ in range(10):
            if self.current_btn_count >= 100:
                return False  # 返回False终止调度
            self.current_btn_count += 1
            btn = Button(text=str(self.current_btn_count), size_hint=(0.2, 0.2))
            self.add_widget(btn)

class ScrollApp(App):
    def build(self):
        return ScrollViewExample()

if __name__ == "__main__":
    ScrollApp().run()

代码说明

  • Clock.schedule_interval(self.add_batch_buttons, 0):调度一个任务,尽可能快地执行但会让Kivy先处理帧渲染,避免阻塞。
  • add_batch_buttons方法:每次添加10个按钮,当按钮总数达到100时返回False,停止调度任务。
  • 保持StackLayout的height: self.minimum_height绑定,确保滚动视图能正确计算可滚动区域。

内容的提问来源于stack exchange,提问作者Pratiyush Pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:51:01