为什么我的 Tkinter 小部件存储为无? [英] Why do my Tkinter widgets get stored as None?
本文介绍了为什么我的 Tkinter 小部件存储为无?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将按钮放入一个数组中,但是当我调用它们时,它们并不存在.如果我打印出我得到的数组:
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()
推荐答案
grid
、pack
和 place
每个 Tkinter 小部件的方法就地操作并且总是返回 None
.这意味着您不能在创建小部件时在同一行调用它们.相反,它们应该在下面的行中调用:
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)
这篇关于为什么我的 Tkinter 小部件存储为无?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文