gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:13 25 4
gpt4 key购买 nike

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

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 删除小部件和标签?

最佳答案

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

  1. self.weightingFuncNameDim2 = None 添加到您的类的 __init__ 方法中,并将您的 if 条件更改为 if self.weightingFuncNameDim2 不是 None 和 self.weightingFuncNameDim2.winfo_exists():

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

  3. 将您的 if block 放在捕获并忽略 AttributeErrors 的 try-except block 中。

关于python - 在删除之前检查小部件是否存在于 tkinter 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28880679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com