Tkinterの:はAttributeError:NoneTypeのオブジェクトが属性を持っていない<属性名>

StackOverflow https://stackoverflow.com/questions/1101750

  •  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'

なぜentryBoxNoneに設定されている?

役に立ちましたか?

解決

gridオブジェクトの、他のすべてのウィジェットの

packplaceEntry機能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のために行うのと同じように!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top