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

Kivy开发圆角按钮时.kv文件报缩进需为8空格倍数错误怎么办

问题解决

核心错误原因

  1. .kv文件缩进不满足Kivy语法要求:错误提示明确要求缩进必须为8空格的整数倍,你当前代码中BoxLayout下的子属性缩进为12空格,不符合规则。
  2. Python代码中MyLayout类同时继承Widget和App,继承逻辑错误,布局类无需继承App。

修复方案

1. 修复KV文件缩进

把BoxLayout下的所有子属性、子控件的缩进统一调整为比BoxLayout多8个空格,修复后的KV代码如下:

<MyLayout>
    BoxLayout:
        orientation: "vertical"
        size: root.width, root.height
        padding: 50
        spacing: 20
        Button:
            text: "Hello World!"
        RoundedButton:
            text: "Goodbye World!"
            pos_hint: {'center_x': 0.5}
            size_hint: (1, .3)
            #background_color: (0/255,255/255,203/255,1)
            #background_normal: ''
<RoundedButton@Button>
    background_color: (0,0,0,0)
    background_normal: ''
    canvas.before:
        Color:
            rgba: (0/255,255/255,203/255,1)
        RoundedRectangle:
            size: self.size
            pos: self.pos
            radius: [58]

2. 修复Python代码的错误继承

MyLayout作为布局控件仅需继承Widget即可,同时移除重复导入的冗余代码,修复后的Python代码如下:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.core.window import Window

Builder.load_file("my.kv")

class MyLayout(Widget):
    def __init__(self,*args,**kwargs):
        super(MyLayout, self).__init__(**kwargs)

class AwesomeApp(App):
    def build(self):
        Window.clearcolor = (1,1,1,1)
        return MyLayout()

if __name__ == '__main__':
    AwesomeApp().run()

额外注意事项

  • KV文件中不要混用制表符(Tab)和空格进行缩进,统一使用空格
  • 所有层级的缩进空格数保持一致,按照你运行环境的要求,使用8空格每级缩进即可正常运行

内容的提问来源于stack exchange,提问作者Sricharan Athanti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:00:02