kyiv:如何通过迭代语句从另一个 class 远程更改标签属性

kviy: How to change Labels properties remotly from another class through an iterative sentence

我需要更改我用循环语句创建的一些标签中的文本。 这是我所做的,但它似乎不起作用

from kivy.app import App
from kivy.uix.label import Label
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.relativelayout import RelativeLayout

class MyUI(BoxLayout):
    def __init__(self, **kwargs):
        super(MyUI, self).__init__(**kwargs)
        for i in range(0, 8):
            lbl = Label(text=str(i*10))
            self.add_widget(lbl)

class MainWindow(BoxLayout):

    my_ui = ObjectProperty()
    new_text = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

    def change_text(self):
        for letter in self.new_text:
            if self.my_ui.lbl.text == '30':
                self.my_ui.lbl.text = letter

class MainApp(App):
    pass

if __name__ == '__main__':
    MainApp().run()

对于 kivy 文件:

MainWindow:

<MainWindow>:
    my_ui: my_ui
    MyUI:
        id: my_ui
    Button:
        text: 'Update Labels'
        on_release: root.change_text()

<MyUI>:

我也不知道如何定位特定标签。我需要通过for循环来初始化标签框布局。

您可以通过保留已创建的 Labels 的列表来做类似的事情。这个版本的 MyUI 是这样做的:

class MyUI(BoxLayout):
    def __init__(self, **kwargs):
        super(MyUI, self).__init__(**kwargs)
        self.lbls = []  # create list of Labels
        for i in range(0, 8):
            lbl = Label(text=str(i*10))
            self.add_widget(lbl)
            self.lbls.append(lbl)  # add this Label to the list

然后在 change_text() 方法中你可以遍历 Labels:

的列表
def change_text(self):
    for letter in self.new_text:
        for lbl in self.my_ui.lbls:  # loop through the list of Labels
            if lbl.text == '30':
                lbl.text = letter

或者,您可以遍历 my_uichildren

    def change_text(self):
        for i, child in enumerate(self.my_ui.children[:]): # or, enumerate(self.my_ui.children[::-1]) depends on the order.
            if child.text == '30':
                child.text = self.new_text[i]