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

2024-09-30 06:16:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打开一个弹出窗口,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秒钟,更改标签文本,然后弹出窗口将打开

有什么问题吗


Tags: textfrom文本importselfid标签pop
1条回答
网友
1楼 · 发布于 2024-09-30 06:16:24

您的代码:

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()

相关问题 更多 >

    热门问题