.pack_forget() 无法正常工作
.pack_forget() not working properly
我在使用 .pack_forget()
功能时遇到问题。如果我写:
a1= Button(root, text='button', width=10, command=buttonclick).pack()
函数a1.pack_forget()
returns错误:
AttributeError: 'NoneType' object has no attribute 'pack_forget'
但是如果我写:
a1= Button(root, text='button', width=10, command=buttonclick)
a1.pack()
函数a1.pack_forget()
正常工作。为什么较短的方式不起作用?
方法pack()
returnsNone
。你必须写:
ai = Button(...)
ai.pack()
第一行将一个Button
对象分配给变量ai
,而类似
ai = Button(...).pack()
会将其分配给 None
。
在python中,当你做x=foo().bar()
时,x
被赋予bar()
的值。所以,在ai=Button(...).pack(...)
的情况下,ai
得到pack(...)
的值。
使用 tkinter,pack(...)
和 grid(...)
和 place(...)
全部 return None
。因此,在您的代码中 ai
设置为 None
。这就是 tkinter 和 python 设计的工作方式。
我在使用 .pack_forget()
功能时遇到问题。如果我写:
a1= Button(root, text='button', width=10, command=buttonclick).pack()
函数a1.pack_forget()
returns错误:
AttributeError: 'NoneType' object has no attribute 'pack_forget'
但是如果我写:
a1= Button(root, text='button', width=10, command=buttonclick)
a1.pack()
函数a1.pack_forget()
正常工作。为什么较短的方式不起作用?
方法pack()
returnsNone
。你必须写:
ai = Button(...)
ai.pack()
第一行将一个Button
对象分配给变量ai
,而类似
ai = Button(...).pack()
会将其分配给 None
。
在python中,当你做x=foo().bar()
时,x
被赋予bar()
的值。所以,在ai=Button(...).pack(...)
的情况下,ai
得到pack(...)
的值。
使用 tkinter,pack(...)
和 grid(...)
和 place(...)
全部 return None
。因此,在您的代码中 ai
设置为 None
。这就是 tkinter 和 python 设计的工作方式。