【问题标题】:grid_forget() not working for dynamic checkbox in tkintergrid_forget() 不适用于 tkinter 中的动态复选框
【发布时间】:2016-02-02 11:49:33
【问题描述】:

我正在创建一个从任何 csv 文件中获取列名的动态复选框,但是在选择选项后我无法清除窗口。

这是一个包含几个名字的列表的示例代码...

# -*- 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()

我想在点击提交按钮后立即获得一个清晰的窗口。

请帮忙!!

【问题讨论】:

    标签: python-3.x for-loop checkbox dynamic tkinter


    【解决方案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 不会破坏窗口,它只会将其隐藏在视图之外。如果您创建新的检查按钮来“替换”隐藏的检查按钮,则会造成内存泄漏。

    【讨论】:

    • 非常感谢 Bryan,有什么办法可以避免内存泄漏?
    • @Suresh2692:销毁小部件,或重复使用它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多