This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>

(3个答案)


2年前关闭。




我将按钮放入一个数组,但是当我调用它们时,它们不存在。如果我打印出数组,我将得到:
{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, ...}

我只是不知道我在做什么错。
from tkinter import *

def main():
    pass

if __name__ == '__main__':
    main()

b={}

app = Tk()
app.grid()

f = Frame(app, bg = "orange", width = 500, height = 500)
f.pack(side=BOTTOM, expand = 1)


def color(x):
   b[x].configure(bg="red") # Error 'NoneType' object has no attribute 'configure'
   print(b) # 0: None, 1: None, 2: None, 3: None, 4: None, 5:.... ect


def genABC():
    for r in range(3):
        for c in range(10):
            if (c+(r*10)>25):
                break
            print(c+(r*10))
            b[c+(r*10)] = Button(f, text=chr(97+c+(r*10)), command=lambda a=c+(r*10): color(a), borderwidth=1,width=5,bg="white").grid(row=r,column=c)

genABC()
app.mainloop()

最佳答案

每个 Tkinter 小部件的 grid pack place 方法就地运行并始终返回 None 。这意味着您不能在创建小部件时在同一行调用它们。相反,它们应该在下面的行中调用:

widget = ...
widget.grid(...)

widget = ...
widget.pack(...)

widget = ...
widget.place(...)

因此,在您的代码中,它将是:
b[c+(r*10)] = Button(f, text=chr(97+c+(r*10)), command=lambda a=c+(r*10): color(a), borderwidth=1,width=5,bg="white")
b[c+(r*10)].grid(row=r,column=c)

关于python - 为什么我的 Tkinter 小部件存储为无?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21592630/

10-15 10:06