首页 > 解决方案 > 如何在进入屏幕之前重置 ToggleButton 状态?

问题描述

我在 screenB 中有很多 ToggleButton,我想在进入屏幕之前重置所有这些按钮。

class screenB(Screen):
    def __init__(self, **kwargs):
        super(MorePage, self).__init__(**kwargs)
        Clock.schedule_once(self.AddWidget)

    def AddWidget(self, *args):
        for i in range(len(all_brand)):
            brand_name = all_brand[i]
            if brand_name[0] == "A" or brand_name[0] == "a":
                self.tbutton = MyToggle(id=brand_name, text=brand_name)
                self.ids.Axxx.add_widget(self.tbutton)
                print(self.tbutton.id)
            elif brand_name[0] == "B" or brand_name[0] == "b":
                self.tbutton = MyToggle(id=brand_name, text=brand_name)
                self.ids.Bxxx.add_widget(self.tbutton)
            elif brand_name[0] == "C" or brand_name[0] == "c":
                self.tbutton = MyToggle(id=brand_name, text=brand_name)
                self.ids.Cxxx.add_widget(self.tbutton)
            ....

    def reset_state(self):
        print(self.ids)
        print(self.ids.Axxx.ids)
        for i in all_brand:    # all brand includes all ids of ToggleButton added in AddWidget
            self.ids[i].state = "normal"

在 .kv 文件中,

<screenB>:
    on_pre_enter:
        root.reset_state()
    Label:
        id: aaa
    Label: 
        id:bbb
    StackLayout:
        id: Axxx
    StackLayout:
        id: Bxxx
    StackLayout:
        id: Cxxx
    ...

我试图reset_state在进入screenB之前打电话。然后我发现self.ids只给了我 aaa, bbb, Axxx, Bxxx, Cxxx 但没有添加任何内容AddWidget。并self.ids.Axxx.ids给了我空的字典。但是,如果我在添加 ToggleButton 后立即打印 tbutton.id,我会得到当前的回报。

那么如何重置所有 ToggleButton 的状态?太感谢了!!

标签: pythonkivytogglebutton

解决方案


我想我现在看到了,self.Axxx.ids没有返回任何内容,因为您在该小部件中没有任何带有ids 的孩子,只需执行此操作即可

for child in self.ids.Axxx.children:
    child.state = "normal"

应该这样做


推荐阅读