Tkinter:AttributeError:NoneType 对象没有属性<属性名称> [英] Tkinter: AttributeError: NoneType object has no attribute <attribute name>

查看:24
本文介绍了Tkinter:AttributeError:NoneType 对象没有属性<属性名称>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了这个简单的 GUI:

I've created this simple 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 按钮时,控制台上出现以下错误:

I get the UI up and running. When I click on the Grab button, I get the following error on the console:

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

为什么 entryBox 设置为 None?

推荐答案

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

The grid, pack and place functions of the Entry object and of all other widgets returns None. In python when you do a().b(), the result of the expression is whatever b() returns, therefore Entry(...).grid(...) will return None.

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

You should split that on to two lines like this:

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

这样您就可以将 Entry 引用存储在 entryBox 中,并且按照您的预期进行布局.如果您将所有 grid 和/或 pack 语句收集在块中,这会带来额外的副作用,使您的布局更易于理解和维护.

That way you get your Entry reference stored in entryBox and it's laid out like you expect. This has a bonus side effect of making your layout easier to understand and maintain if you collect all of your grid and/or pack statements in blocks.

这篇关于Tkinter:AttributeError:NoneType 对象没有属性&lt;属性名称&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆