首页 > 解决方案 > 无法获得价值。返回 AttributeError:“NoneType”对象没有属性“get”

问题描述

在为标签和按钮使用框架之前,我尝试使用 get 方法。但是使用框架后,总是返回属性错误。

我已经尝试过这段没有框架的代码,它完美地返回。

root = Tk()
head = Label(root, text='LOGIN', font=('', 35), pady=10)
head.pack()
logf = Frame(root, padx=90, pady=90)
Label(logf, text='Username: ', font=('', 20), pady=5, padx=5).grid(sticky=W)
e1 = Entry(logf, bd=5, font=('Calibri', 15)).grid(row=0, column=1)
Label(logf, text='Password: ', font=('', 20), pady=5, padx=5).grid(sticky=W)
e2 = Entry(logf, bd=5, font=('Calibri', 15), show='*').grid(row=1, column=1)
Button(logf, text=' Quit ', bd=3, font=('', 15), padx=5, pady=5, command=root.quit).grid()
Button(logf, text=' Login', bd=3, font=('', 15), padx=5, pady=5, command=update).grid(row=2,column=1)
logf.pack()
username=("%s"%((e1.get())))
password=("%s"%((e2.get())))

我应该在变量中获取用户名和密码的值。

标签: pythonuser-interfacetkinter

解决方案


您需要将 .grid() 放在下一行。

root = Tk()
head = Label(root, text='LOGIN', font=('', 35), pady=10)
head.pack()
logf = Frame(root, padx=90, pady=90)
Label(logf, text='Username: ', font=('', 20), pady=5, padx=5).grid(sticky=W)
e1 = Entry(logf, bd=5, font=('Calibri', 15))
e1.grid(row=0, column=1)
Label(logf, text='Password: ', font=('', 20), pady=5, padx=5).grid(sticky=W)
e2 = Entry(logf, bd=5, font=('Calibri', 15), show='*')
e2.grid(row=1, column=1)
Button(logf, text=' Quit ', bd=3, font=('', 15), padx=5, pady=5, command=root.quit).grid()
Button(logf, text=' Login', bd=3, font=('', 15), padx=5, pady=5, command=update).grid(row=2,column=1)
logf.pack()
username=("%s"%((e1.get())))
password=("%s"%((e2.get())))

这个:

e2 = Entry(logf, bd=5, font=('Calibri', 15), show='*').grid(row=1,   column=1)

将 e2 设置为 .grid() 的返回值,这没什么。这根本不会创建输入字段变量/引用。这意味着您稍后将无法使用 e2.get() 获取输入字段的值,因为 e2 引用不存在。

这个:

e2 = Entry(logf, bd=5, font=('Calibri', 15), show='*')
e2.grid(row=1, column=1)

创建 e2 变量/引用。这会以您可以使用 e2.get() 获取输入字段中的值的方式创建条目。


推荐阅读