Tkinter Entry绑定StringVar调用smtplib报'StringVar'无encode属性错误
问题原因
错误AttributeError: 'StringVar' object has no attribute 'encode'是因为你直接将Tkinter的StringVar对象传入了smtplib的相关方法,smtplib要求入参是普通Python字符串,而StringVar是Tkinter封装的特殊变量类型,需要调用它的.get()方法才能拿到存储的实际字符串值。
修复步骤
- 在
send_mail函数中,所有用到from_、passphrase、to、title这些StringVar变量的地方,都加上.get()取实际值 - 你当前代码里的正文Text组件没有和变量绑定,且
place()方法返回None,需要调整Text组件的创建方式,后续才能正确读取正文内容
修复后的完整代码
import smtplib from tkinter import * root = Tk() root.geometry('600x450') root.resizable(0,0) root.title("Gmail Post Service - Pre-alpha") def send_mail(): global title,text,from_,passphrase,to,message # 调用.get()获取StringVar存储的实际字符串 from_val = from_.get() pass_val = passphrase.get() to_val = to.get() title_val = title.get() # 读取Text组件的正文内容,Text组件用get("1.0", END)取内容 text_val = t.get("1.0", END) mail = smtplib.SMTP('smtp.gmail.com',587) mail.ehlo() message = 'Subject: {}\n\n{}'.format(title_val,text_val) mail.starttls() mail.login(from_val,pass_val) mail.sendmail(from_val,to_val,message) mail.close() from_= StringVar() to= StringVar() passphrase= StringVar() title= StringVar() Label(root, text = 'From:', font = 'arial 12 bold').place(x= 5 , y = 20) from2=Entry(root, width=30,textvariable=from_).place(x=55,y=25) Label(root, text = 'Password:', font = 'arial 12 bold').place(x= 250 , y = 20) passphrase2=Entry(root, width=30,textvariable=passphrase, show="*").place(x=340,y=25) Label(root, text = 'To:', font = 'arial 12 bold').place(x= 20 , y = 50) to2=Entry(root, width=30,textvariable=to).place(x=55,y=55) Label(root, text = 'Title:', font = 'arial 12 bold').place(x= 5 , y = 95) title2=Entry(root, width=80,textvariable=title).place(x=55,y=100) # 先创建Text对象再调用place,保留Text实例用于读取内容 t = Text(root, height=16, width=60) t.place(x=55,y=140) Button(root,text ='\u2386',command=lambda:[send_mail()], font = 'arial 15 bold',height = 1,width = 6,bg = 'ghost white', padx = 2).place(x=455 ,y =404) root.mainloop()
额外注意事项
- 谷歌邮箱默认不允许普通密码直接通过第三方SMTP登录,你需要先在谷歌账号设置中开启「应用专用密码」,使用生成的应用专用密码代替普通账号密码登录,否则会报登录失败错误
- 密码输入框新增了
show="*"参数,避免输入时密码明文显示
内容的提问来源于stack exchange,提问作者Tim's
相关产品推荐
相关产品推荐

