如何有效地为tkinter框架添加大量按钮?

tha*_*guy 6 python tkinter button

我想为Tkinter添加10个按钮,名为One to Ten.我基本上只使用了暴力方法,在我的应用程序类的init函数中添加每个按钮.它可以工作,但我想最小化所使用的代码,以提高效率,例如使用数据结构来保存所有按钮.

我正在考虑使用a buttonBox来容纳所有按钮,但我不确定我是否可以通过操作grid()按钮放置按钮我想要的方式.

self.one = Button(frame, text="One", command=self.callback)
self.one.grid(sticky=W+E+N+S, padx=1, pady=1)

self.two = Button(frame, text="Two", command=self.callback)
self.two.grid(sticky=W+E+N+S, row=0, column=1, padx=1, pady=1)

self.three = Button(frame, text="Three", command=self.callback)
self.three.grid(sticky=W+E+N+S, row=0, column=2, padx=1, pady=1)

# ...

self.ten = Button(frame, text="Ten", command=self.callback)
self.ten.grid(sticky=W+E+N+S, row=1, column=4, padx=1, pady=1)
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我一种提高效率的方法,比如数据结构吗?

unu*_*tbu 5

相反命名的按钮self.oneself.two等等,这将是更方便的通过索引列表,如提及他们self.button

如果按钮执行不同的操作,则只需将按钮与回调明确关联。例如:

name_callbacks=(('One',self.callback_one),
                ('Two',self.callback_two),
                ...,
                ('Ten',self.callback_ten))
self.button=[]
for i,(name,callback) in enumerate(name_callbacks):
    self.button.append(Button(frame, text=name, command=callback))
    row,col=divmod(i,5)
    self.button[i].grid(sticky=W+E+N+S, row=row, column=col, padx=1, pady=1)
Run Code Online (Sandbox Code Playgroud)

如果所有按钮都执行相似的操作,则一次回调就可以为所有按钮提供服务。由于回调本身不能接受参数,因此可以设置一个回调工厂以通过闭包传递参数:

def callback(self,i): # This is the callback factory. Calling it returns a function.
    def _callback():
        print(i) # i tells you which button has been pressed.
    return _callback

def __init__(self):
    names=('One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten')
    self.button=[]
    for i,name in enumerate(names):
        self.button.append(Button(frame, text=name, command=self.callback(i+1)))
        row,col=divmod(i,5)
        self.button[i].grid(sticky=W+E+N+S, row=row, column=col, padx=1, pady=1)
Run Code Online (Sandbox Code Playgroud)