【发布时间】:2021-02-28 23:10:36
【问题描述】:
使用 Kivy 1.11.1 和 Python 3.7.6。
我有这个特殊的问题,我无法在任何地方找到答案。
我想在按钮按下时调用的方法中两次更新 Label 的文本(此处为:statusLabel)(在本例中为display_hello_status()。但似乎Kivy 仅在方法调用完成后 更新接口 - 仅导致对标签文本的最新更改呈现。
您可以在下面找到有问题的方法的代码。
main.py:
import time
import kivy
from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.app import App
kivy.require('1.11.1')
class WindowManager(ScreenManager):
pass
class PrintHello(Screen):
username = ObjectProperty(None)
status = ObjectProperty(None)
def display_hello_status(self):
# Inform about process of generating hello text.
self.status.text = "printing hello..." # this text is never displayed.
# Pretend something is happening in the background.
time.sleep(2)
self.username.text = f"Hello, {self.username.text}!"
# Display information indicating successful printing.
self.status.text = "printed!"
class MyApp(App):
pass
if __name__ == '__main__':
MyApp().run()
my.kv:
WindowManager:
PrintHello:
<PrintHello>:
username: username_text_input
status: status_label
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
padding: 8
spacing: 8
Label:
text: "Your name:"
size_hint_y: None
height: 32
bold: True
TextInput:
id: username_text_input
size_hint_y: None
height: 32
multiline: False
FloatLayout:
Button:
text: "Print"
size_hint: 0.2, 0.2
pos_hint: {"center_x": 0.6, "y": 0.4}
on_release: root.display_hello_status()
BoxLayout:
orientation: "horizontal"
size_hint: 0.2, 0.2
pos_hint: {"center_x": 0.2, "y": 0.4}
padding: 4
Label:
text: "Status:"
bold: True
Label:
id: status_label
text: "off"
background_color: 0, 0, 0, 0 # black
color: 1, 1, 1, 1 # white
所以我想要实现的是:
- 通过文本和颜色更改通知用户某些过程正在进行。
- 在后台做一些处理,需要一些时间(模拟
time.sleep(2)。 - 显示程序成功完成进程的信息。
问题是:我该怎么做?如何强制 Widget(在本例中为标签)在方法中间更新?
谢谢!
【问题讨论】:
-
@JohnAnderson 我按照建议实现了该问题的独立版本。感谢您的帮助!
标签: python user-interface kivy label