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

标签 python user-interface tkinter radio-button

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

我尝试了 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

最佳答案

当你销毁时,你试图销毁一些尚未打包的东西,因为你在 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()

关于python - 即使我使用 destroy/pack_forget,Tkinter Widget 也不会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49968706/

相关文章:

python - 在 ubuntu 16.04 中安装 pyodbc 和 pymssql 时遇到障碍

python - OpenCV 通过填充调整大小

python - 拆分数字模式

python - 打开第二个 python 文件 (tkinter)

python - 为什么 Tkinter 在 Windows 上会出现堆栈溢出?

python - 你好!我在 tkinter 网格对齐和按钮大小方面遇到一些问题

python - tkinter (不确定我的错误可能是由于 .destroy() 造成的)

python - 在Windows中安装Jupyter Notebook

Java jTable 来自 ArrayList 对象的数据并通过其他方法更新

c# - 强制 BindingSource 更新数据/模型