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

Kivy切换窗口时如何更新TextInput的text参数?

Kivy切换窗口时无法更新TextInput内容的解决方案

问题根源

你在MainWindow的on_press方法中调用ThirdWindow().write()时,新建了一个ThirdWindow实例,而不是操作ScreenManager中已经加载的那个ThirdWindow对象。这个新实例从未被添加到界面中,所以即使修改了它的TextInput内容,也不会在屏幕上显示。

修复方案

通过ScreenManager的get_screen()方法获取已经存在的ThirdWindow实例,再调用它的write()方法。

修改后的Python代码

from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.animation import Animation
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
from functools import partial

Window.size = (500, 700)
Window.clearcolor = "#1b1a28"


class MainWindow(Screen):
    def go_window(self, window, widget, *args):
        self.manager.current = window
        animate = Animation(duration=0.4, background_color=(96/255, 85/255, 83/255, 1), color=(1,1,1,1))
        animate.start(widget)

    def animation(self, widget, *args):
        animate = Animation(duration=0.1)
        animate += Animation(size_hint=(1.2,1.2),duration=0.1,background_color=(0,0,0,-1))
        animate += Animation(size_hint=(1,1),duration=0.1,color=(0,0,1,0))
        animate.start(widget)

    def on_press(self, widget, *args):
        if widget.gid == "accounts":
            self.animation(widget)
            Clock.schedule_once(partial(self.go_window, "second", widget), 0.5)
        if widget.gid == "notes":
            self.animation(widget)
            Clock.schedule_once(partial(self.go_window, "third", widget), 0.5)
            # 关键修改:获取已存在的ThirdWindow实例
            self.manager.get_screen("third").write()

class SecondWindow(Screen):
    pass


class ThirdWindow(Screen):
    def __init__(self, **kwargs):
        super(ThirdWindow, self).__init__(**kwargs)
        Window.bind(on_request_close=self.exit_program)

    def go_back(self, widget, *args):
        if widget.gid == "notes":
            print(self.ids.notes2.text)
        self.manager.current = "main"

    def write(self):
        self.ids.notes2.text = "test"
        print(1)


    def exit_program(self, *args):
        print(self.ids.notes2.text)


class WindowManager(ScreenManager):
    pass


kv = Builder.load_file("widgets.kv")


class MyApp(App):
    def build(self):
        return kv

if __name__ == "__main__":
    MyApp().run()

说明

  • self.manager.get_screen("third")会从ScreenManager中获取名为"third"的已加载屏幕实例,这个实例就是KV文件中定义的那个ThirdWindow。
  • 调用这个实例的write()方法,修改的就是界面上实际显示的TextInput控件,所以内容会正常更新。

内容的提问来源于stack exchange,提问作者Александр Безпалый

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:54:24