Python 3- Tkinter destroy()对动态检查按钮不起作用

时间:2019-03-01 15:56:45

标签: python python-3.x tkinter

我的代码获取一个计算机名称,然后浏览文件夹,并拉出这些文件夹的名称以创建复选框,然后将其显示给用户,以便他们可以选择要使用的文件夹。但是,如果更改计算机名称,我要删除所有当前复选框的名称,并从新计算机名称显示新名称。我已经尝试了多种方法destroy(),但是它不起作用。我知道这与使用网格有关。

def CreateBoxes(folders):

    if len(checkBoxList) != 0: #if there are already checkboxes then delete
        for i in folders:
            chk.destroy()

    count=0
    for i in folders: #Creates checkbuttons for each folder received
        checkBoxList[i]=IntVar()
        chk = Checkbutton(window, text=str(i), variable=checkBoxList[i])
        chk.grid(row=0+count,column=4)
        count += 1

1 个答案:

答案 0 :(得分:2)

执行chk.destroy()时,Python无法理解chk的含义。您可能在该函数的较早执行中创建了一个名为chk的变量,但是在该函数返回后该名称不再存在。

一个可能的解决方案是保留对每个复选框的外部引用。然后,您将可以在以后访问每个数据库并将其销毁。

checkboxes = []

def CreateBoxes(folders):
    if len(checkBoxList) != 0: #if there are already checkboxes then delete
        for chk in checkboxes:
            chk.destroy()
        checkboxes.clear()

    count=0
    for i in folders: #Creates checkbuttons for each folder received
        checkBoxList[i]=IntVar()
        chk = Checkbutton(window, text=str(i), variable=checkBoxList[i])
        chk.grid(row=0+count,column=4)
        checkboxes.append(chk)
        count += 1