Tkinterの:はAttributeError:NoneTypeのオブジェクトが属性を持っていない<属性名>
-
12-09-2019 - |
質問
私はこのシンプルな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
に設定されている?
解決
grid
オブジェクトの、他のすべてのウィジェットの pack
、place
とEntry
機能None
を返します。あなたがa().b()
を行う際のpythonでは、式の結果は、したがって、b()
がEntry(...).grid(...)
を返します。何でもNone
戻り、です。
あなたはこのように2行にそれを上に分割する必要があります:
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)
の2行に
entryBox=Entry(root,width=60)
entryBox.grid(row=2, column=1,sticky=W)
あなたはすでに正しくgrabBtn
のために行うのと同じように!
所属していません StackOverflow