Kivy:如何在不关闭弹出窗口的情况下更新弹出标签文本
Posted
技术标签:
【中文标题】Kivy:如何在不关闭弹出窗口的情况下更新弹出标签文本【英文标题】:Kivy: How to update popup Label Text without dismiss the popup 【发布时间】:2020-09-17 09:37:34 【问题描述】:我想打开一个弹出窗口并在 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()
但是BEFORE打开弹窗它会休眠3秒,更改标签文本然后弹窗就会打开!!
有什么问题?
【问题讨论】:
【参考方案1】:您的代码:
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()
【讨论】:
以上是关于Kivy:如何在不关闭弹出窗口的情况下更新弹出标签文本的主要内容,如果未能解决你的问题,请参考以下文章