调用函数时清除框架的内容

时间:2018-05-17 09:36:15

标签: python tkinter

我的程序根据单选按钮的选择创建不同的小部件。一切都很好,但如果选择了另一个单选按钮,我似乎无法清除旧的小部件。这里的建议:(https://stackoverflow.com/a/15995920/3924118)不起作用。这是相关的代码。

来自主程序:

root = Tk()
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
secondframe = ttk.Frame(mainframe)
secondframe.grid(column=4, row=3)
secondframe.columnconfigure(0, weight=1)
secondframe.columnconfigure(0, weight=1)

然后功能:

def pct_from_duration():
    """ Calculate needed pct from target duration"""
    tgt_dur_entry = ttk.Entry(mainframe, width=4, textvariable=tgt_dur_inp)
    tgt_dur_entry.grid(column=5, row=3, sticky=(W, E))
    for widget in secondframe.winfo_children():
        widget.destroy()
    ttk.Label(secondframe, textvariable=pct_bond_end).grid(column=1, row=1)
    ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=5, row=4, sticky=W)

FWIW,我没有收到任何错误消息,它实际上并没有删除小部件。这都是python 3.6。

1 个答案:

答案 0 :(得分:1)

也许这会有所帮助......我是你的功能的一个例子,它正在发挥作用(Python 3.5)

import tkinter as tk
from tkinter import *
from tkinter import ttk

class GUI:

    def __init__(self, master):

        def pct_from_duration():
            tgt_dur_entry = ttk.Entry(mainframe, width=4)
            tgt_dur_entry.grid(column=5, row=3, sticky=(W, E))
            for widget in secondframe.winfo_children():
                widget.destroy()
            l3 = ttk.Label(secondframe, text = 'Label').grid(column=1, row=1)
            b2 = ttk.Button(mainframe, text="Calculate").grid(column=5, row=4, sticky=W)

        self.master = master
        mainframe = ttk.Frame(master)
        mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
        mainframe.columnconfigure(0, weight=1)
        mainframe.rowconfigure(0, weight=1)
        secondframe = ttk.Frame(mainframe)
        secondframe.grid(column=4, row=3)
        secondframe.columnconfigure(0, weight=1)
        secondframe.columnconfigure(0, weight=1)
        l = Label(secondframe, text = 'Child_mainframe')
        l.grid()
        l2 = Label(mainframe, text = 'Child_secondframe')
        l2.grid()
        r1 = Radiobutton(master, text="Radiobutton", value=1, command = pct_from_duration).grid()

root = Tk()
root.rowconfigure(0, weight = 1)
root.columnconfigure(1, weight=1)
root.columnconfigure(0, weight=1)
root.columnconfigure(0, weight=2)
my_gui = GUI(root)
root.mainloop()