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

如何在Kivy多屏幕场景中使用Splitter组件?

问题解决方案

你遇到的问题源于Splitter组件使用方式错误和Screen切换时的渲染缓存残留,以下是修复后的完整代码及说明:

修复后主文件

import kivy
from kivy.app import App 
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager , Screen, NoTransition


class TestScreen1(Screen):
    pass
class TestScreen2(Screen):
    pass
class Manager(ScreenManager):
    pass

class MyApp(App):
    def build(self):
        # 用原始字符串避免路径转义错误
        return Builder.load_file(r"D:\MainProject\TestFiles\my.kv")


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

修复后KV文件

Manager:
    # 禁用过渡动画,消除切换时的渲染残留
    transition: NoTransition()
    TestScreen1:
    TestScreen2:


<TestScreen1>:
    name:"abc1"
    # 禁用Screen缓存,防止重影
    cache: False
    BoxLayout:
        orientation: 'horizontal'
        # 第一个固定宽度的输入框/组件
        TextInput:
            text:"左侧固定输入框"
            size_hint_x: None
            width: 180
        # Splitter包裹可调整大小的输入框
        Splitter:
            sizable_from: "left"
            # 初始占比,支持拖拽调整
            size_hint_x: 0.6
            TextInput:
                text:"可调整大小的输入框"
        Button:
            text: "next"
            size_hint_x: None
            width: 80
            on_press: root.manager.current="abc2"

<TestScreen2>:
    name:"abc2"
    cache: False
    BoxLayout:
        orientation: 'horizontal'
        TextInput:
            text:"左侧固定输入框"
            size_hint_x: None
            width: 180
        Splitter:
            sizable_from: "left"
            size_hint_x: 0.6
            TextInput:
                text:"另一个可调整的输入框"
        Button:
            text: "pre"
            size_hint_x: None
            width: 80
            on_press: root.manager.current="abc1"

关键修复说明

  • Splitter用法修正:
    • Splitter需要直接包裹你要调整大小的内容组件(如TextInput),而非与其他组件平级。
    • 给Splitter设置size_hint_x或固定尺寸,确保布局中存在可拖拽调整的空间。
    • 搭配size_hint_x: None+固定width的组件,让Splitter调整时仅改变自身区域大小。
  • 重影问题解决:
    • 给ScreenManager添加transition: NoTransition(),避免过渡动画引发的渲染残留。
    • 给每个Screen设置cache: False,禁用渲染缓存,防止切换后旧内容残留。
  • 路径优化:主文件中使用原始字符串加载KV,避免转义符导致的路径解析错误。

内容的提问来源于stack exchange,提问作者random stuff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:55:24