即使我使用destroy / pack_forget,Tkinter Widget也不会消失

时间:2018-04-22 17:21:17

标签: python user-interface tkinter radio-button

我正在学习GUI,作为测试,我正在尝试开发一个带有两个单选按钮的框架,一个用于随机模拟,一个用于文件输入模拟。当我想要文件输入模拟时需要文件名,所以我的意思是我的第二个单选按钮,通过switch_entry命令打包新的Label / Entry。如果选择了第一个单选按钮,则调用的方法也应该删除Label和条目。

我尝试了pack_forget和destroy,但结果是我通过选择第二个单选按钮来创建de Label / Entry,但是不能通过选择第一个来销毁它们。当我选择第一和第二单选按钮时,GUI会不断添加标签/条目集。代码和图片如下:

import tkinter as tk


class InterRiver(tk.Frame):

    def __init__(self, master = None):
        self.mode = tk.StringVar(value="Random")
        tk.Frame.__init__(self, master)
        self.lblChooseMode = tk.Label(self, text="Opções do Simulador").pack(side="top")
        self.rdModeRndm = tk.Radiobutton(self, text = "Rio Aleatório", value = "Random", variable = self.mode,
                                         command = self.switch_entry).pack(anchor="w", side="top")
        self.rdModeFile = tk.Radiobutton(self, text = "Rio a partir de arquivo", value= "File", variable = self.mode,
                                         command = self.switch_entry).pack(anchor ="w", side="top")
        self.btnStart= tk.Button(self, text = "Simular", command = simular).pack(side = "bottom")
        self.lblCycles = tk.Label(self, text = "Número de Ciclos").pack(side="top")
        self.ntyCycles = tk.Entry(self).pack(side="top")
    def switch_entry(self):
        lblFile = tk.Label(self, text="Insira o nome do arquivo")
        ntyFile = tk.Entry(self)
        if self.mode.get() == "File":
           lblFile.pack(side="top")
           ntyFile.pack(side="top")
        else:
           lblFile.destroy()
           ntyFile.destroy()
if __name__ == "__main__":
    w = tk.Tk()
    InterRiver(w).pack()
    w.title("Bears and Fishes")
    w.mainloop()

Repeated Label/Entries

1 个答案:

答案 0 :(得分:2)

当你在摧毁时,你试图摧毁你曾经拥挤过的东西,因为你在switch_entry的开头创建了它,然后打包或销毁它。您的switch_entry函数应为:

    if self.mode.get() == "File":
       self.lblFile = tk.Label(self, text="Insira o nome do arquivo")
       self.ntyFile = tk.Entry(self)
       self.lblFile.pack(side="top")
       self.ntyFile.pack(side="top")
    else:
       self.lblFile.destroy()
       self.ntyFile.destroy()

实际上,更快捷的方法是将这些行放在__init__中:

       self.lblFile = tk.Label(self, text="Insira o nome do arquivo")
       self.ntyFile = tk.Entry(self)

然后在switch_entry

    if self.mode.get() == "File":
       self.lblFile.pack(side="top")
       self.ntyFile.pack(side="top")
    else:
       self.lblFile.pack_forget()
       self.ntyFile.pack_forget()