Why do my Tkinter widgets get stored as None? [dup

2018-12-31 16:46发布

This question already has an answer here:

I'm putting my buttons into an array but when I call them they are not there. If I print out the array I get:

{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, ...}

I just don't know what I am doing wrong.

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()

1条回答
余生请多指教
2楼-- · 2018-12-31 17:27

The grid, pack, and place methods of every Tkinter widget operate in-place and always return None. This means that you cannot call them on the same line as you create a widget. Instead, they should be called on the line below:

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

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

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

So, in your code, it would be:

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)
查看更多
登录 后发表回答