【发布时间】:2018-05-12 06:49:55
【问题描述】:
我刚开始使用 tkinter,偶然发现了一个我自己无法解决的问题:
我想自己写一个小部件,我称之为口袋。这实际上是我的窗口的一部分,可以滑动打开或隐藏。
class pocket(tk.Frame):
def __init__(self, parent, master=None, expand_Bool=True):
tk.Frame.__init__(self, parent)
self.master = master
self.Content = tk.Frame(self)
self.Button_on = tk.Button(self,text='Open',command=lambda: self.expand())
self.Button_hide = tk.Button(self,text='Hide',command=lambda: self.hide())
self.Content.grid(row=1,column=0)
self.Button_on.grid(row=0,column=0)
self.Button_hide.grid(row=0,column=0)
if expand_Bool:
self.expand()
else:
self.hide()
def expand(self):
self.Button_on.grid_remove()
self.Button_hide.grid()
self.Content.grid()
def hide(self):
self.Button_on.grid()
self.Button_hide.grid_remove()
self.Content.grid_remove()
def get_contentframe(self):
return self.Content
if __name__=='__main__':
root=tk.Tk()
pocket1 =pocket(root)
pocket1.grid(row=0,column=0)
label1=tk.Label(pocket1.get_contentframe(),text='Text')
label1.grid(row=1,column=1)
root.mainloop()
“小部件”本身运行良好。但是当我尝试关闭窗口时,我收到一条错误消息:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\...\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\...\tkinter\__init__.py", line 2055, in destroy
for c in list(self.children.values()): c.destroy()
File "C:\...\tkinter\__init__.py", line 2300, in destroy
if self._name in self.master.children:
AttributeError: 'NoneType' object has no attribute 'children'
我怎样才能避免这个错误?还是有更好的方法来做到这一点?
提前致谢。
问候
【问题讨论】:
-
你使用
tkinter.after()还是threads?您可能必须在关闭程序之前停止它们。 -
BWT:代替
command=lambda: self.expand()你可以使用command=self.expand(没有lambda和()) -
好吧,
self.master确实是None,那么你为什么期望它有一个名为children的属性?
标签: python tkinter parent children attributeerror