在删除之前检查tkinter中是否存在小部件

时间:2015-03-05 14:49:32

标签: python tkinter

我正在使用下拉菜单创建多个小部件。我想在删除之前检查小部件是否存在(来自下拉菜单上的先前选择)。我使用以下代码:

self.ndim_options, self.ndim_options_var = self.DropdownMenuCommand(("1","2","3"),'-',"Number of indirect dimensions","-")

def DropdownMenuCommand(self,options,status,name,row):

    if row == "-":
      row = self.row

    optionLabel = tk.Label(self.frame, bg='turquoise')
    optionLabel["text"] = name
    optionLabel.grid(row=row, column=0, sticky='w')
    var = tk.StringVar(self)
    var.set(status)
    w = tk.OptionMenu(self.frame, var, *options, command = self.setdimensionproperties)
    w.config(bg = 'paleturquoise')
    w["menu"].config(bg = 'paleturquoise')
    w.grid(row=row, column=1)
    self.row += 1
    return w, var

def setdimensionproperties(self,val):
    row = self.RowEnd

    if val == "3":  #Set parameters for a 4D (3 indirect dimensions)

      #Remove any existing weighting functions
      if self.weightingFuncNameDim2.winfo_exists():
        self.weightingFuncNameDim2.grid_remove()

      self.weightingFuncNameDim2, self.weightingFuncNameDim2_var = self.DropdownMenu(("sinebell","gaussian", "sinebell2"),'-', "Weighting function dimension 2",row)

但是,如果尚未创建窗口小部件,则会出现属性错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
    return self.func(*args)
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 3141, in __call__
    self.__callback(self.__value, *args)
  File "test.py", line 224, in setdimensionproperties
    if self.weightingFuncNameDim2.winfo_exists():
AttributeError: Window instance has no attribute 'weightingFuncNameDim2'

理想情况下,如果窗口小部件存在,我希望if语句返回1,如果不存在,我希望0,这就是我认为的.winfo_exists()。我怎样才能解决这个错误?另外,如何确保.grid_remove删除小部件和标签?

2 个答案:

答案 0 :(得分:5)

我看到三种可能的解决方案。按优先顺序排列:

  1. self.weightingFuncNameDim2 = None添加到您的班级“__init__方法”中,并将if条件更改为if self.weightingFuncNameDim2 is not None and self.weightingFuncNameDim2.winfo_exists():

  2. 将您的条件更改为if hasattr(self, "weightingFuncNameDim2") and self.weightingFuncNameDim2.winfo_exists():

  3. if块放在try-except块中,捕获并忽略AttributeErrors。

答案 1 :(得分:4)

  

...但是,如果未创建窗口小部件,我会收到属性错误:

最好的解决方案是确保您的班级始终具有该属性,即使该小部件不存在也是如此。将其设置为None,然后在创建窗口小部件时将其重置。然后您的条件成为:

  if self.weightingFuncNameDim2 is not None:
    self.weightingFuncNameDim2.grid_remove()
  

如何确保.grid_remove同时删除小部件和   标签

grid_remove将始终只从视图中删除一个小部件。但是,如果该窗口小部件包含其他窗口小部件,那么其他窗口小部件也将从视图中删除。