Tk窗口返回AttributeError:__len__

时间:2013-12-04 07:04:31

标签: python class tkinter tk

在这里,我开始创建一个带有文本字段的TK窗口,但是当我运行它时,我得到了错误

Exception in Tkinter callback
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "School.py", line 31, in begin
    emulatorI=emulator()
  File "School.py", line 20, in __init__
    code.pack(self.root)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1868, in pack_configure
    + self._options(cnf, kw))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1105, in _options
    cnf = _cnfmerge(cnf)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 114, in _cnfmerge
    for c in _flatten(cnfs):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1826, in __getattr__
    return getattr(self.tk, attr)
AttributeError: __len__

来自模块内部。我究竟做错了什么?我对课程很新,所以我可能在课程设置中做错了。

我在OS 10.9上运行python 2.7

class emulator:
    def __init__(self):
        self.root=Tk()
        self.root.geometry("500x500")

        self.root.title("Python")

        code=Text(self.root)
        code.pack(self.root)

        self.root.mainloop()

emulatorI=emulator()

2 个答案:

答案 0 :(得分:1)

问题在于

code.pack(self.root)

pack函数通常不接受除关键字参数之外的参数,因此应该只调用

code.pack()

非常奇怪的错误的原因是pack 可以采用位置参数,该参数应该是选项字典。尝试将Tk实例视为字典时,由于缺少__len__方法,它失败了。

答案 1 :(得分:0)

code.pack(self.root)的目的是什么?

pack的参数是放置方向,例如side,padding,fill,anchor等 (见http://effbot.org/tkinterbook/pack.htm)。