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

Python-Kivy:使用ScreenManager访问MDTextField触发KeyError问题求助

问题根因

你代码中存在两个完全独立的ScreenManager实例,你访问的是未绑定KV组件规则的无效实例:

  • 你手动定义的全局变量sm,自行添加了MenuScreen、SecondScreen实例,但这两个实例没有加载KV中写的组件配置,ids字典为空,自然找不到input_username这个id
  • 实际渲染在界面上、带输入框组件的ScreenManager,是build方法中Builder.load_string返回的实例,你之前没有正确访问这个实例

修正后的完整代码

from kivymd.app import MDApp
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
import sys

screen_helper = """
ScreenManager: 
    MenuScreen:
        name: 'menu'
    SecondScreen:
        name: 'second'

<MenuScreen>:
    MDToolbar:
        title: "Menu Screen"
        pos_hint: {"top": 1}
        anchor_title: "center"
        md_bg_color: (0/255, 0/255, 0/255, 1)
    Image:
        source: "Logo_h_black.png"
        pos_hint: {"center_x": 0.5, "center_y": 0.75}
        size_hint_x: (0.25)
        size_hint_y: (0.25)
    MDTextField:
        id: input_username
        hint_text: "Username"
        size_hint: (0.5, 0.1)
        pos_hint: {"center_x": 0.5, "center_y": 0.55}
        font_size: 20
        mode: "rectangle"
    MDTextField:
        id: input_password
        hint_text: "Password"
        size_hint: (0.5, 0.1)
        pos_hint: {"center_x": 0.5, "center_y": 0.45}
        font_size: 20
        mode: "rectangle"
    MDFillRoundFlatButton:
        text: "LOG IN"
        font_size: 17
        pos_hint: {"center_x": 0.5, "center_y": 0.25}
        on_press: app.loginFunction()
    
<SecondScreen>:
    MDLabel:
        text: 'Profile'
        halign: 'center'
    MDRectangleFlatButton:
        text: 'Back'
        pos_hint: {'center_x':0.5,'center_y':0.1}
        on_press: root.manager.current = 'menu'
        

"""

class MenuScreen(Screen):
    pass

class SecondScreen(Screen):
    pass

class myApp(MDApp):
    def loginFunction(self, args=None):          
        if args is None:
           args = sys.argv
        # 直接访问app自身的root,就是Builder加载出来的有效ScreenManager实例
        mainScreenInstance = self.root.get_screen('menu')
        username = mainScreenInstance.ids["input_username"].text
        password = mainScreenInstance.ids["input_password"].text
        print(username)
        print(password)

    def build(self):
        screen = Builder.load_string(screen_helper)
        return screen

myApp().run()

修改后运行点击登录按钮即可正常打印输入框的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:45:02