我的代码获取计算机名称,然后查找文件夹并提取这些文件夹的名称来创建复选框,然后将它们显示给用户,以便他们可以选择要使用的文件夹。但是,如果您更改计算机名称,我想删除所有当前复选框的名称,并显示新计算机名称中的新名称。我已经以多种方式尝试过 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/