繁体   English   中英

Tkinter: AttributeError: NoneType object 没有属性<attribute name></attribute>

[英]Tkinter: AttributeError: NoneType object has no attribute <attribute name>

我创建了这个简单的 GUI:

from tkinter import *

root = Tk()

def grabText(event):
    print(entryBox.get())    

entryBox = Entry(root, width=60).grid(row=2, column=1, sticky=W)

grabBtn = Button(root, text="Grab")
grabBtn.grid(row=8, column=1)
grabBtn.bind('<Button-1>', grabText)

root.mainloop()

我让 UI 启动并运行。 当我单击Grab按钮时,控制台上出现以下错误:

C:\Python> python.exe myFiles\testBed.py
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python\lib\lib-tk\Tkinter.py", line 1403, in __call__
    return self.func(*args)
  File "myFiles\testBed.py", line 10, in grabText
    if entryBox.get().strip()=="":
AttributeError: 'NoneType' object has no attribute 'get'

为什么entryBox设置为None

Entry对象和所有其他小部件的gridpackplace函数返回None 在 python 中,当您执行a().b()时,表达式的结果是b()返回的任何内容,因此Entry(...).grid(...)将返回None

你应该把它分成两行,如下所示:

entryBox = Entry(root, width=60)
entryBox.grid(row=2, column=1, sticky=W)

这样,您就可以将Entry参考存储在entryBox中,并且它的布局与您期望的一样。 如果您在块中收集所有grid和/或pack语句,这具有使您的布局更易于理解和维护的额外副作用。

更改此行:

entryBox=Entry(root,width=60).grid(row=2, column=1,sticky=W)

分为这两行:

entryBox=Entry(root,width=60)
entryBox.grid(row=2, column=1,sticky=W)

就像你已经正确地为grabBtn做的那样!

Python3.8+版本的替代解决方案,允许使用walrus operator将所有这些放在一行中:

(entryBox := Entry(root, width=60)).grid(row=2, column=1, sticky=W)

现在entryBox将引用Entry小部件并被打包。

对于每行管理的字符,我可以建议这样的事情:

(var := Button(
    text='fine', command=some_func, width=20, height=15, activebackground='grey'
)).grid(row=0, column=0, columnspan=0, rowspan=0, sticky='news')

但在这一点上,不妨“正常”地这样做(正如其他答案所建议的那样)

资料来源:

要让entryBox.get()访问get()方法,您需要Entry对象,但Entry(root, width=60).grid(row=2, column=1, sticky=W)返回 None。

entryBox = Entry(root, width=60)创建一个新的条目对象。

此外,您不需要entryBox = entryBox.grid(row=2, column=1, sticky=W)因为它将用 None 重写entryBox


只需将entryBox = entryBox.grid(row=2, column=1, sticky=W)替换为

entryBox = Entry(root, width=60)
entryBox.grid(row=2, column=1, sticky=W)

Tkinter不允许将小部件的定义与.grid().pack()放在同一行。 而不是把entryBox = Entry(root, width=60).grid(row=2, column=1, sticky=W)

您应该输入:

entryBox = Entry(root, width=60)
entryBox.grid(row=2, column=1, sticky=W)

由于Tkinter模块的编程方式,这是必需的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM