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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:35:17