簡體   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