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
相关产品推荐
相关产品推荐

