简体   繁体   English

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

[英]Python 3- Tkinter destroy() not working for dynamic checkbuttons

My code gets a computer name then looks through folders and pulls these folders' names to create checkboxes, then it shows them to the user so they can select the ones to work with. 我的代码获取了一个计算机名称,然后浏览了文件夹并拉出了这些文件夹的名称以创建复选框,然后将其显示给用户,以便他们可以选择要使用的文件夹。 However, if you change the computer name I want to delete all the current checkboxes' names, and display the new names from the new computer name. 但是,如果更改计算机名称,我要删除所有当前复选框的名称,并从新计算机名称显示新名称。 I have tried destroy() in multiple ways, but it just doesn't work. 我已经尝试了多种方法destroy(),但是它不起作用。 I know it has to do with working with grids. 我知道这与使用网格有关。

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

When chk.destroy() executes, Python does not understand what chk refers to. chk.destroy()执行时,Python无法理解chk所指的是什么。 You may have created a variable named chk in an earlier execution of that function, but that name ceased to exist after the function returned. 您可能在该函数的较早执行中创建了一个名为chk的变量,但是该名称在函数返回后就不复存在了。

One possible solution is to keep an external reference to each of your checkboxes. 一种可能的解决方案是保留对每个复选框的外部引用。 Then you will be able to access each one at a later time and destroy them. 然后,您将可以在以后访问每个数据库并销毁它们。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM