Kivy 删除小部件

Kivy remove widget

我在删除带有标签的小部件后遇到了问题 这是相关的代码段:

    logi= True
    if data == []:

        logn =Label(text= "Incorrect Username",color=(190,0,0,1),
                     pos_hint={"right":1.035,"top":1.14})
        self.add_widget(logn)

        logu =Label(text= "Incorrect Password",color=(190,0,0,1),
                pos_hint={"right":1.035,"top":1.04})
        self.add_widget(logu)

        logi= False

    if logi == True:

        textinput.text=''
        textinput2.text=''

        if 'logn' in locals() and 'logu' in locals() :
            self.remove_widget(logn)   
            self.remove_widget(logu)

添加小部件后,我似乎无法删除它们,如果我删除 if 'logn' in locals() and 'logu' in locals() : 语句,我每次在没有上述 if 语句的情况下测试它时都会收到错误 "Local variable referenced before assignment "我确保已添加小部件

我假设您两次输入此方法(第一次数据==[] 第二次数据=[...])。所以你应该把你的变量放在手边(把它们放在实例上 - self

logi= True
if data == []:

    self.logn =Label(text= "Incorrect Username",color=(190,0,0,1),
                 pos_hint={"right":1.035,"top":1.14})
    self.add_widget(self.logn)

    self.logu =Label(text= "Incorrect Password",color=(190,0,0,1),
            pos_hint={"right":1.035,"top":1.04})
    self.add_widget(self.logu)

    logi= False

if logi == True:

    textinput.text=''
    textinput2.text=''

    if hasattr(self, 'logn'): #check that we put something here before...
        self.remove_widget(self.logn)   
        self.remove_widget(self.logu)

记下我添加的所有地方self ...