删除所有子组件后如何添加子组件?

时间:2015-03-02 14:43:15

标签: python user-interface python-3.x tkinter

目前,我正在执行以下代码以删除gui上的子窗口小部件

for child in infoFrame.winfo_children(): child.destroy()

然而,gui不会给gui增加另一个孩子。例如,以下代码中的任何一行

people.place(in_ = gui, x = 1, y = 1, width = 422, height = 449)

people.grid(row = 0, column = 0)

在gui上放置一个标签。我使用以下代码创建标签

people = Label(text = "Default", fg = "black", bg = "white")

编辑我被要求添加我的gui代码,所以这里是:

def initializeGui(name = "Default"):
    GUI = Tk()
    GUI.geometry("423x450+200+200")
    GUI.title(name)
    return GUI

def buttonAnswers(): #This is what I'm focusing on
    gui.title("Answers")
    for child in gui.winfo_children():
        child.destroy()
    return True
    people = Label(text = "Default", fg = "black", bg = "white")
    #people.place(in_ = gui, x = 1, y = 1, width = 422, height = 449)
    people.grid(row = 0, column = 0)

def buttonTest(): #This will be the same as the button above but will open a different gui
    gui.title("Test")
    for child in gui.winfo_children():
        child.destroy()
    return True

    question = Label(text = "Do you want to see the Answers or take the Test?", fg = "black", bg = "white")
    question.grid(row = 0, column = 1)
    checkAns = Button(gui, text = "Answers", command = buttonAnswers, fg = "black", width=10)
    checkAns.grid(row = 1, column = 0)    

gui = initializeGui("School Test")
label = Label(text = "Do you want to see the Answers or take the Test?", fg = "black", bg = "white")
label.grid(row = 0, column = 1)
answers = Button(gui, text = "Answers", command = buttonAnswers, fg = "black", width=10)
questions = Button(gui, text = "Test", command = buttonTest, fg = "black", width=10)
answers.grid(row = 1, column = 0)
questions.grid(row = 1, column = 2)`

该问题的解决方案如下:

def buttonAnswers(): #This is what I'm focusing on
    gui.title("Answers")
    for child in gui.winfo_children():
        child.destroy()
    return True
    people = Label(text = "Default", fg = "black", bg = "white")
    #people.place(in_ = gui, x = 1, y = 1, width = 422, height = 449)
    people.grid(row = 0, column = 0)

在for循环下面包含return True,阻止程序继续。因此,删除return True允许程序继续使用脚本并将其他子项添加到表单中。

def buttonAnswers(): #This is what I'm focusing on
    gui.title("Answers")
    for child in gui.winfo_children():
        child.destroy()
    people = Label(text = "Default", fg = "black", bg = "white")
    #people.place(in_ = gui, x = 1, y = 1, width = 422, height = 449)
    people.grid(row = 0, column = 0)

1 个答案:

答案 0 :(得分:3)

在销毁窗口小部件之后但在添加任何新窗口小部件之前,您有一个return语句。添加新窗口小部件的代码永远不会被执行。