Python 3-Tkinter destroy() 不适用于动态检查按钮

标签 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

最佳答案

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

关于Python 3-Tkinter destroy() 不适用于动态检查按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54948157/

相关文章:

python - 在 Python 中捕获所有异常

python - tkinter 显示当前标签,删除上一个

python - Scrapy - 获取正在解析的项目的索引?

python - 错误的 Voigt 输出/具有不对称 x 输入的卷积

Python线程挂了?

python - Sphinx 无法导入名称 gql

python - 无法导入名称 'pb'

python - Model.clean() 与 Model.clean_fields()

python - tkinter 中的 GIF 故障

python - Tkinter .after 模块只是延迟了 GUI 的打开