python tkinter packing

大憨熊 提交于 2021-01-29 03:50:20

问题


Could someone please explain why when you have an plain widget as one line Code A works

Entry(root, width=10).pack(side=LEFT,anchor=W)

but when you name it or attach a command to it, Code A no longer works and gives you Error Message B

self.my_entry = Entry(root, width=10).pack(side=LEFT,anchor=W)

and you must pack using a seperate line?

self.my_entry = Entry(root, width=10)
self.my_entry.pack(side=LEFT,anchor=W)

Code A

self.my_entry.get()

Error Message B

AttributeError: 'NoneType' object has no attribute 'get'

回答1:


The pack method returns None. So

self.my_label = Label(root, text="My Label").pack(side=LEFT,anchor=W)

sets self.my_label to None. That is why further commands using self.my_label no longer work.

You've found the solution; call pack on a separate line:

self.my_label = Label(root, text="My Label")
self.my_label.pack(side=LEFT,anchor=W)


来源:https://stackoverflow.com/questions/8896697/python-tkinter-packing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!