I want to create a column of 10 buttons and have them numbered in order.
Is there a simpler way to do it using for
loops that I can add the text to these buttons rather than coding out each button line by line?
This is what I have but it only puts the the number 10 text in each button? I want each button numbered starting from 1 thru 10.
from tkinter import *
root = Tk()
#Create Buttons
def create_buttons():
number_text = []
for nums in range(0,10):
number_text.append(str(nums))
for col in range(10):
for num in number_text:
buttons = Button(root, font=30, text = num, padx=15, pady=10)
buttons.grid(row=0, column=col)
create_buttons()
root.mainloop()
CodePudding user response:
It might be because the 1st button gets overlapped by 2nd ... so on to 9th button. So, you see 9 on top, which hides other buttons.
Try a different way -
from tkinter import *
root = Tk()
#Create Buttons
def create_buttons():
number_text = [*range(1,10 1)] # Or you could just do this in your way
for col in range(10):
buttons = Button(root, font=30, text = number_text[col] , padx=15, pady=10)
buttons.grid(row=0, column=col)
create_buttons()
root.mainloop()
This will take the index number_text[col]
and show the buttons.
CodePudding user response:
This is my solution for your problem,
from tkinter import *
root = Tk()
#Create Buttons
def create_buttons():
for num in range(1,11):
buttons = Button(root, font=30, text =str(num), padx=15, pady=10)
buttons.grid(row=0, column=num)
create_buttons()
root.mainloop()
Actually, you can solve this one easily. Every time you should try to reduce the complexity of the program. Don't think much. So I supposed this code much easier to solve your problem. Here I using only one loop and that loop I use for the given name for the button and also the given column number. You using the same parameters for the Button widget and grid manipulation. When we use another name for the button you should want to create a list. That code example is given below,
from tkinter import *
root = Tk()
button_name=[f'number_{i}' for i in range(10)]
#Create Buttons
def create_buttons():
for num in range(1,11):
buttons = Button(root, font=30, text =str(button_name[num-1]), padx=15, pady=10)
buttons.grid(row=0, column=num)
create_buttons()
root.mainloop()