71

この単純な 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ですか?

4

4 に答える 4

126

オブジェクトおよび他のすべてのウィジェットのおよび関数は、gridを返します。Python で を実行すると、式の結果は何でも返されるため、が返されます。packplaceEntryNonea().b()b()Entry(...).grid(...)None

次のように 2 行に分割する必要があります。

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

そうすれば、Entry参照が保存されentryBox、期待どおりにレイアウトされます。gridこれには、すべてのand/orpackステートメントをブロックにまとめると、レイアウトが理解しやすくなり、維持しやすくなるという副次的な効果があります。

于 2009-07-09T03:53:34.080 に答える
12

この行を変更します。

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

于 2009-07-09T05:55:49.843 に答える