Kivy Python:如何通过Popup修改主窗口的Label内容?
问题根源
你遇到的核心问题是:点击弹窗的OK按钮时,Factory.MyLayout().targetID(...) 会创建一个全新的MyLayout实例,你修改的是这个新实例的Label文本,而不是当前界面上正在显示的那个MyLayout实例的Label。所以控制台能打印出修改后的值,但界面上的原实例完全没变化。
解决方案
直接通过App的root属性获取当前显示的主布局实例,修改它的Label,同时关闭弹窗。具体修改如下:
修改KV语言部分的Content弹窗OK按钮
将原代码中Content里的OK按钮的on_release事件替换为:
MDFlatButton: adaptive_height: True text: 'OK' on_release: app.root.targetID('yourLbl', file_chooser.selection) root.dismiss()
完整修改后的代码
from kivymd.app import MDApp from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.uix.popup import Popup from kivymd.uix.button import MDFlatButton KV = ''' #:import Factory kivy.factory.Factory <MyLayout>: yourLbl: yourLbl orientation: 'vertical' ScrollView: padding: '20dp' MDGridLayout: md_bg_color: 1, 0, 0, 1 adaptive_height: True cols: 1 MDLabel: id: yourLbl text: 'hello' size: self.texture_size MDRaisedButton: text: 'Choose File' md_bg_color: 1, 0, 0, .6 on_release: Factory.Content().open() <Content>: size_hint: .7, .7 MDBoxLayout: orientation: 'vertical' padding: '20dp' md_bg_color: 1, 1, 1, 1 ScrollView: MDGridLayout: adaptive_height: True cols: 1 MDLabel: id: myL text: 'Hello' MDFlatButton: adaptive_height: True text: 'OK' on_release: app.root.targetID('yourLbl', file_chooser.selection) root.dismiss() FileChooserIconView: id: file_chooser on_selection: root.selected(file_chooser.selection) ''' Builder.load_string(KV) class MyLayout(BoxLayout): def targetID(self, tID, value): self.yourLbl.text = value[0] print(self.yourLbl.text) class Content(Popup): def close(self): self.dismiss() def selected(self, filename): try: self.ids.myL.text = filename[0] except: pass class FileChooserApp(MDApp): def build(self): return MyLayout() if __name__ == '__main__': FileChooserApp().run()
说明
app.root指向的是App的build方法返回的MyLayout实例,也就是当前界面上显示的主布局,修改它的Label才会在界面上生效。- 加上
root.dismiss()是为了在点击OK后关闭弹窗,提升用户体验。
内容的提问来源于stack exchange,提问作者Moe Kyaw Thu
相关产品推荐
相关产品推荐

