Kivy:如何在不关闭弹出窗口的情况下更新弹出标签文本

Kivy: How to update popup Label Text without dismiss the popup

我想打开一个弹出窗口并在 3 秒后更改弹出标签的文本。

我试试这个代码:

from kivy.app import App
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button
import time

Builder.load_string('''
<SimpleButton>:
    on_press: self.fire_popup()
<SimplePopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: True
    title: 'Hello world!!'
    Label:
        id: lbl_id
        text: 'Default Text'
''')


class SimplePopup(Popup):
    pass


class SimpleButton(Button):
    text = "Fire Popup !"

    def fire_popup(self):
        pop = SimplePopup()
        pop.open()

        time.sleep(3)
        pop.ids.lbl_id.text = "Changed Text"


class SampleApp(App):
    def build(self):
        return SimpleButton()


SampleApp().run()

但是打开弹出窗口之前它会休眠 3 秒,更改标签文本然后弹出窗口将打开!!

有什么问题?

您的代码:

time.sleep(3)

正在停止主线程,因此在该代码完成之前,GUI 不会发生任何事情。您应该像这样使用 Clock.schedule_once() 安排文本更改:

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button

Builder.load_string('''
<SimpleButton>:
    on_press: self.fire_popup()
<SimplePopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: True
    title: 'Hello world!!'
    Label:
        id: lbl_id
        text: 'Default Text'
''')


class SimplePopup(Popup):
    pass


class SimpleButton(Button):
    text = "Fire Popup !"

    def fire_popup(self):
        self.pop = SimplePopup()
        self.pop.open()
        Clock.schedule_once(self.change_text, 3)

    def change_text(self, dt):
        self.pop.ids.lbl_id.text = "Changed Text"


class SampleApp(App):
    def build(self):
        return SimpleButton()


SampleApp().run()