我是Kivy的新手,我不得不认为这是可能的,但我无法弄清楚 - 如何在按下按钮时更新Kivy标签,但只能通过参考在Python中的Kivy id? (我试图这样做的原因是因为在我的实际应用程序中,我希望一次更新几个标签,我希望我可以在等效按钮内完成所有操作在我的应用程序)。
在下面的简单示例中,我只是尝试按下按钮,然后将标签更新为“已更新!”'
非常感谢!
我的Python代码:
button_pressed
我的kv档案:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
import random
class TestingWidget(BoxLayout):
# This is the kv id of the Label I would like to update
label_to_update = StringProperty('')
# This is the action I would like to happen when the button is pressed
def button_pressed(self):
label_to_update.text = 'Updated!'
class TestButtonApp(App):
def build(self):
return TestingWidget()
if __name__ == '__main__':
TestButtonApp().run()
答案 0 :(得分:1)
按下按钮时,您肯定会更新所有标签。只需为每个人创建一个StringProperty并执行你现在正在做的事情。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.lang import Builder #used because I didn't want to create two files
import random
Builder.load_string('''
<TestingWidget>:
BoxLayout:
orientation: 'horizontal'
Button:
text: 'test'
on_press: root.button_pressed()
Label:
id: label_to_update
text: root.label_to_update
''')
class TestingWidget(BoxLayout):
# This is the kv id of the Label I would like to update
label_to_update = StringProperty('Trying to get this to update')
#default text set
# This is the action I would like to happen when the button is pressed
def button_pressed(self):
self.label_to_update = 'Updated!'
class TestButtonApp(App):
def build(self):
return TestingWidget()
if __name__ == '__main__':
TestButtonApp().run()