我刚刚开始使用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'
我怎样才能避免这个错误?还是有更好的方法来做到这一点?
提前谢谢。
问候
答案 0 :(得分:0)
问题是
self.master = master
坦率地说,当你执行
时tk.Frame.__init__(self, parent)
然后它会自动创建变量self.master
并指定parent
。
self.master = parent
你不必这样做。
在您的代码中master
是None
,所以最后得到
self.master = None
因此它无法访问parent
并且在尝试关闭子项时遇到问题。
完整代码
import tkinter as tk
class Pocket(tk.Frame):
def __init__(self, master=None, expand_bool=True):
tk.Frame.__init__(self, master)
self.content = tk.Frame(self)
self.button_on = tk.Button(self, text='Open', command=self.expand)
self.button_hide = tk.Button(self, text='Hide', command=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()