I want to add 10 buttons to Tkinter, named One to Ten. I basically just used the brute force method, adding each button as I went, in the init function of my application’s class. It works, but I want to minimize the code used, to be more efficient, such as using a data structure to hold all the buttons.
I was thinking of using a buttonBox to hold all the buttons in, but I was not sure if I could manipulate the placement via grid() to place the buttons how I wanted.
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)
Can anyone show me a way to make this more efficient, such as a data structure?
Instead of naming the buttons
self.one,self.two, etc., it would be more convenient to refer to them by indexing a list, such asself.button.If the buttons do different things, then you just have to explicitly
associate buttons with callbacks. For example:
If the buttons all do similar things, then one callback may suffice to service them all. Since the callback itself can’t take arguments, you can setup a callback factory to pass the arguments in through a closure: