Kivy中ScreenManager按钮点击时获取/设置TextInput内容求助
解决Kivy中SecondWindow内TextInput的内容获取与设置问题
问题背景
尝试获取或设置Kivy应用中SecondWindow内GridLayout下id为text_input的TextInput内容时,出现以下错误:
- 使用
self.manager.get_screen('second').ids.text_input.text时,报错:AttributeError: 'super' object has no attribute '__getattr__' - 使用
self.root.ids["text_input"].text时,报错:AttributeError: 'SecondWindow' object has no attribute 'root'
错误原因
核心问题出在kv文件的id定义格式错误:所有id被添加了双引号(比如id: "text_input")。Kivy的kv语言中,id是标识符,不需要加引号,加引号会导致ids字典无法正确识别控件,从而无法通过ids属性访问目标控件。
另外,kv文件中部分size属性使用了带引号的字符串(比如size: ("92dp", "92dp")),这会导致布局计算异常,需要修正为数值格式。
修复方案
1. 修正kv文件中的id和格式
将所有带双引号的id改为无引号的标识符,同时修正size属性的格式:
WindowManager: transition: NoTransition() FirstWindow: SecondWindow: <FirstWindow>: name: "first" BoxLayout: orientation: "vertical" size: root.width, root.height Button: text: "Go To Next Screen" on_release: app.root.current = "second" <SecondWindow>: name: "second" GridLayout: id: Container cols: 2 rows: 1 ScrollView: id: SideMenuScrollView size_hint: (0.3, 1) do_scroll_y: True do_scroll_x: False StackLayout: id: SideMenuStack size_hint_y: None height: self.minimum_height Button: size_hint: (None, None) size: (92, 92) Button: size_hint: (None, None) size: (92, 92) GridLayout: size_hint: (1, 1) id: MyGrid spacing: 10 padding: 10 cols: 1 rows: 2 TextInput: id: text_input multiline: False text: "" size_hint: (1, None) height: 30 Button: text: "Do Stuff" on_release: root.DoStuff() size_hint: (1, None) height: 70
2. 在Python代码中访问TextInput
在SecondWindow的DoStuff方法中,直接通过self.ids.text_input访问目标控件,实现获取和设置内容:
from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder class WindowManager(ScreenManager): pass class FirstWindow(Screen): pass class SecondWindow(Screen): def DoStuff(self): # 获取TextInput的当前内容 current_text = self.ids.text_input.text print("当前输入内容:", current_text) # 设置TextInput的内容 self.ids.text_input.text = "已更新的内容" kv = Builder.load_file('new_window.kv') class AwesomeApp(App): def build(self): return kv if __name__ == "__main__": AwesomeApp().run()
3. 跨Screen访问TextInput
如果需要从其他Screen(比如FirstWindow)访问SecondWindow的TextInput,可以通过ScreenManager获取目标Screen后操作:
# 在FirstWindow的方法中添加如下代码 def some_method(self): second_screen = self.manager.get_screen('second') # 设置内容 second_screen.ids.text_input.text = "从FirstWindow设置的内容" # 获取内容 input_text = second_screen.ids.text_input.text print(input_text)
内容的提问来源于stack exchange,提问作者Alex Woodhead
相关产品推荐
相关产品推荐

