AttributeError:Entry实例没有属性'__len__'

时间:2013-05-05 21:33:19

标签: python tkinter

我是python的新手,我一直在玩Tkinter和requests来尝试创建一个可以登录我的Web应用程序的简单程序。我收到了以下错误:

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 1410, in __call__
    return self.func(*args)
  File "test.py", line 35, in login
    c.post('http://fruro.com/login.php', data=self.payload)
  File "/Users/Peter/Desktop/fruroPy/fruro/lib/python2.7/site-packages/requests/sessions.py", line 399, in post
    return self.request('POST', url, data=data, **kwargs)
  File "/Users/Peter/Desktop/fruroPy/fruro/lib/python2.7/site-packages/requests/sessions.py", line 343, in request
    prep = req.prepare()
  File "/Users/Peter/Desktop/fruroPy/fruro/lib/python2.7/site-packages/requests/models.py", line 222, in prepare
    p.prepare_body(self.data, self.files)
  File "/Users/Peter/Desktop/fruroPy/fruro/lib/python2.7/site-packages/requests/models.py", line 375, in prepare_body
    body = self._encode_params(data)
  File "/Users/Peter/Desktop/fruroPy/fruro/lib/python2.7/site-packages/requests/models.py", line 81, in _encode_params
    return urlencode(result, doseq=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1311, in urlencode
    len(v)
AttributeError: Entry instance has no attribute '__len__'

我一直想弄清楚几个小时可能出错的地方,但我不知道自己做错了什么。

这是我正在使用的代码:

from Tkinter import *
from requests import session

class Login:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.emLabel = Label(frame, text="Email:")
        self.emLabel.pack(side=LEFT)

        self.email = Entry(frame, width=15)
        self.email.pack(side=LEFT)

        self.pasLabel = Label(frame, text="Password:")
        self.pasLabel.pack(side=LEFT)

        self.password = Entry(frame, show="*", width=15)
        self.password.pack(side=LEFT)

        self.hi_there = Button(frame, text="Login", command=self.login)
        self.hi_there.pack()

    def login(self):

        self.payload = {
            'action': 'login',
            'email': self.email,
            'password': self.password 
        }

        with session() as c:
            c.post('http://fruro.com/login.php', data=self.payload)
            self.request = c.get('http://fruro.com')
            print self.request.headers
            print self.request.text


root = Tk()
login = Login(root)
root.title("Login to your account")
root.mainloop()

任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:2)

问题出在这一行,

c.post('http://fruro.com/login.php', data=self.payload)

这种情况正在发生,因为您传递的dict data参数的值是Entry小部件的引用,而不是这些小部件的内容。因此,当Requests尝试获取len时,您会收到错误,因为Entry未实现__len__(不是您想要的)。要解决此问题,请将self.payload更改为

self.payload = {
        'action': 'login',
        'email': self.email.get(),      # call get method to return
        'password': self.password.get() # the value in the Entry widgets
    }