首页 > 解决方案 > Kivy:我如何重置复选框活动值

问题描述

当我在屏幕之间切换时,我想清除标记的复选框。当我更改屏幕时,标记的框保持选中状态。

我想如果我在切换到另一个屏幕时找到一种方法来更改复选框的激活,我的问题就会得到解决。

但我不知道该怎么做。

我的代码也有一定数量的复选框,我只选择了其中的六个。我的主文件中的函数是计算它们。

我的 main.py

class SkillChose(Screen):
    checkboxvalues = {}
    for i in range(1, 21):
        checkboxvalues["s{}".format(i)] = -2
    def __init__(self,**kwargs):
        super(SkillChose,self).__init__(**kwargs)
        self.click_count = 0
        self.skills=[]

    def click_plus(self,check,id):
        if check is True:
            self.click_count+=1
            self.checkboxvalues[id]=1
        return True
    def click_extraction(self,id):
        if self.checkboxvalues[id]==1:self.click_count-=1
        self.checkboxvalues[id]=0
        return False
    def control(self,id):
        if id==0:return False
        count=0
        for open in self.checkboxvalues.values():
            if open==1:
                count+=1
        for i,j in self.checkboxvalues.items():
            print(i,j)
        if count<6:
            return True
        else:
            return False


我的.kv 文件

<SkillChose>:
    name:"skill"
    BoxLayout
        ScrollView:
            size: self.size
            GridLayout:
                id: grid
                size_hint_y: None
                row_default_height: '50sp'
                height: self.minimum_height
                cols:2
                Label:
                Label:
                Label:
                    text:"skill1"
                CheckBox:
                    value:"s1"
                    active:(root.click_plus(self.active,self.value) if root.control(self.value) else False ) if self.active else root.click_extraction(self.value)
                Label:
                    text:"skill2"
                CheckBox:
                    value:"s2"
                    active:(root.click_plus(self.active,self.value) if root.control(self.value) else False ) if self.active else root.click_extraction(self.value)
                Label:
                    text:"skill3"
                CheckBox:
                    value:"s3"
                    active:(root.click_plus(self.active,self.value) if root.control(self.value) else False ) if self.active else root.click_extraction(self.value)

标签: pythonpython-3.xkivy

解决方案


离开屏幕时清除CheckBox' 属性需要以下增强功能(kv 文件和 Python 脚本) 。active

.kv 文件

使用ScreenManager on_leave事件来调用回调,例如reset_checkbox()

片段 - kv 文件

<SkillChose>:
    name:"skill"

    on_leave: root.reset_checkbox()

    BoxLayout:
        ...

py文件

  • 添加导入语句,from kivy.uix.checkbox import CheckBox
  • 使用for循环遍历GridLayout:via的孩子ids.grid
  • 使用isinstance()函数检查CheckBox小部件

片段 - Py 文件

class SkillChose(Screen):
    ...
    def reset_checkbox(self):
        for child in reversed(self.ids.grid.children):
            if isinstance(child, CheckBox):
                child.active = False    
    ...

推荐阅读