2016-02-02 64 views
0

我正在創建一個動態複選框,用於從任何csv文件中提取列名稱,但是我無法在選擇選項後清除窗口。grid_forget()不適用於tkinter中的動態複選框

這是一個包含有幾個名字列表中的示例代碼...

# -*- coding: utf-8 -*- 
""" 
Created on Tue Feb 2 16:20:54 2016 

------------------------Tkinter------------------------- 

@author: Suresh 
""" 

import tkinter as tk 
from tkinter import ttk #themed tk 
win = tk.Tk() 
win.title("py") 
win.geometry("970x500") 
win.configure() 
#selection_frame = Frame(tk) 

alabel = ttk.Label(win, text="Demo CheckBox",anchor='center') 
alabel.grid(column=70, row=0) 
alabel.configure(foreground='darkblue') 

global check_box 

def clearwindow(): 
    check_box.grid_forget() 

feat_names = ['Tv','Radio','Newspaper','Internet','Transport','Sports'] 

for i in range(len(feat_names)): 
     feat = tk.StringVar() 
     check_box = tk.Checkbutton(win, text=feat_names[i], variable=feat, state ='normal') 
     check_box.grid(column=30, row=i+14, sticky=tk.W)   
     check_box.deselect() 


action = ttk.Button(win, text="Submit", command=clearwindow)  
action.grid(column=4, row=30) 


win.mainloop() 

我想,只要我點擊提交按鈕獲得清晰的窗口。

Plz help !!

回答

1

您必須保留對所有複選框的引用,而不僅僅是一個。

checkboxes = [] 
for i in range(len(feat_name)): 
    ... 
    check_box = tk.Checkbutton(...) 
    checkboxes.append(check_box) 
    ... 

然後,只需遍歷所有的列表:

def clearwindow(): 
    for check_box in checkboxes: 
     check_box.grid_forget() 

要知道,只是打電話grid_forget不破壞窗戶,它只是從視圖中隱藏它。如果您創建新的檢查按鈕來「替換」隱藏的按鈕,您將創建內存泄漏。

+0

非常感謝Bryan,有什麼方法可以節省內存泄漏? – Suresh2692

+0

@ Suresh2692:銷燬小部件或重新使用它們。 –