I'm making buttons from a list on a command and I was wondering how I can make it so after a certain number of buttons it starts creating buttons on a different column?
For example:
list = [1,2,3,4,5,6,7,8,9,10]
def func(number):
some_function()
for number in list:
button = Button(root, text=number, command=lambda x=number: func(x))
button.grid()
So after say 5 buttons made I was wondering if I could make it to continue making buttons on the second column?
After trying to find an answer I was unsuccessful so any help is much appreciated thank you.
CodePudding user response:
You can calculate the row and column using the index of the item in the list and divmod()
function. Also better don't use keyword list
as the variable name.
# don't use keyword list as variable name
itemlist = [1,2,3,4,5,6,7,8,9,10]
def func(number):
some_function()
for idx, number in enumerate(itemlist):
col, row = divmod(idx, 5) # change 5 to other value to suit your case
button = Button(root, text=number, command=lambda x=number: func(x))
button.grid(row=row, column=col)