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

运行Kivy的AnchorLayout示例代码无输出的原因是什么?

Kivy AnchorLayout测试代码问题点及修复方案
  • 变量名引用错误:代码中定义的按钮实例名为self.Button_1,但调用add_widget时错误传入了不存在的self.Button,运行会直接抛出AttributeError异常
  • 布局嵌套逻辑错误:自定义的AnchorLayoutDemo本身已经继承自AnchorLayout,内部额外实例化的self.layout没有被添加到AnchorLayoutDemo自身的子控件树中,即使修复变量名问题界面也不会显示任何内容
  • 颜色值参数不规范:Kivy框架中颜色参数RGBA的取值范围为0-1,代码中传入的25.85、25等值远大于上限,会导致颜色显示异常
  • 类名覆盖问题:实例化App时直接用类名MyApp作为实例变量名,覆盖了原类定义,属于不规范的编码习惯

修复后可正常运行的代码如下:

from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button


class AnchorLayoutDemo(AnchorLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 直接给当前继承的AnchorLayout设置锚点参数,无需额外嵌套布局
        self.anchor_x = "left"
        self.anchor_y = "top"
        # 颜色值除以255转换为0-1范围,保留原设定色调
        self.Button_1 = Button(
            text="Button-1",
            size_hint=(.2, .2),
            background_color=(0, 25.85/255, 25/255, 1),
            color=(25.85/255, 0, 25.45/255, 1),
            border=(25, 25, 25, 25)
        )
        # 直接把按钮添加到当前布局实例中
        self.add_widget(self.Button_1)

class MyApp(App):
    def build(self):
        return AnchorLayoutDemo()


if __name__ == '__main__':
    # 避免覆盖类名,使用独立实例变量
    app = MyApp()
    app.run()

内容的提问来源于stack exchange,提问作者Md Nafi Rahat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:27:03