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

Python Kivy运行报错App.root must be an _instance_ of Widget求助

问题触发原因
  • 核心原因:你自定义的LVAD_GUIDemo类没有继承Kivy的Widget体系子类,哪怕你做了实例化操作,也不属于合法的App根组件类型,所以抛出Invalid instance in App.root错误。
  • 其他配套错误:
    • KV规则中绑定的verify_credentials()方法名,和类中实际定义的verifyCred()方法名不匹配
    • 自定义布局类不需要写build()方法,build()是App类独有的方法,布局的初始化逻辑应该放在__init__中
    • 若要使用self.manager做页面跳转,需要先配套使用ScreenManager并将登录页定义为Screen子类,否则跳转逻辑会报错
修复方案
  1. 给LVAD_GUIDemo类增加父类继承,单页面测试可先继承BoxLayout,需要多页面跳转则继承Screen
  2. 统一方法名,匹配KV规则和类内定义
  3. 移除自定义布局类中的build()方法,将初始化逻辑移到__init__中
  4. 按需补充ScreenManager相关逻辑实现页面跳转
可运行修复代码示例
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput

Builder.load_string("""
<LVAD_GUIDemo>:
    orientation: 'vertical'
    TextInput:
        id: username
        hint_text: "Kullanıcı Adı"
    TextInput:
        id: password
        password: True # 隐藏密码输入
        hint_text: "Şifre"
    Button:
        text: "Giriş Yap"
        on_release: root.verifyCred()
""")       


class LVAD_GUIDemo(BoxLayout):
    def __init__(self, **kwargs):
        super(LVAD_GUIDemo, self).__init__(**kwargs)
        # 若不需要动态添加控件可删除下方add_widget逻辑,KV中已经定义了相关组件
        username = TextInput(hint_text="Kullanıcı Adı:", size_hint=(1,0.06))
        self.add_widget(username)
        password = TextInput(hint_text="Şifre:", size_hint=(1,0.06), password=True)
        self.add_widget(password)
        touchBarbtn1 = Button(text='Giriş Yap', size_hint_y=0.05,size_hint_x=1)
        touchBarbtn1.bind(on_press=lambda x: self.deneme())
        self.add_widget(touchBarbtn1)

    def deneme(self):
        print("ehe")

    def verifyCred(self):
        if self.ids["username"].text == "kaan" and self.ids["password"].text == "kaan1999":
            print("登录成功")
            # 如需页面跳转需先定义ScreenManager,再调用 self.manager.current = "user"

class LVAD_GUIDemoApp(App):
    def build(self):
        return LVAD_GUIDemo()


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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:27:04