List and Dictionaries can be very useful when dealing with large amounts or potently large amounts of widgets.
Below is a bit of code to accomplish what you described in your question.
I use a list called self.my_entries
to store all the entries that will be created based on the value of what the user types in. I also added a little error handling just in case the user tries to type in something other than a number or nothing is enter when the button is pressed.
The first entry and button are placed on the root window and for all of the entry fields that are going to be created we add a frame below the first button. This will allow us to manage the entry fields a bit easier if we want to reset the field later.
from tkinter import *
class Example(Frame):
def __init__(self):
Frame.__init__(self)
self.pack()
self.my_entries = []
self.entry1 = Entry(self)
self.entry1.grid(row = 0, column = 0)
Button(self, text="Set Entry Fields", command=self.create_entry_fields).grid(row = 1, column = 0)
self.frame2 = Frame(self)
self.frame2.grid(row = 2, column = 0)
def create_entry_fields(self):
x = 0
try:
x = int(self.entry1.get())
if x != 0:
for i in range(x):
self.my_entries.append(Entry(self.frame2))
self.my_entries[i].grid(row=i, column=1)
f_label = Label(self.frame2, text="Label {}: ".format(i+1))
f_label.grid(row=i, column=0)
Button(self.frame2, text="Print to console", command=self.print_all_entries).grid(row=x, column=0, sticky = "nsew")
Button(self.frame2, text="Reset", command=self.clear_frame2).grid(row=x, column=1, sticky = "nsew")
except:
print("Invalid entry. Only numbers are allowed.")
def print_all_entries(self):
for i in self.my_entries:
print(i.get())
def clear_frame2(self):
self.my_entries = []
self.frame2.destroy()
self.frame2 = Frame(self)
self.frame2.grid(row = 2, column = 0)
if __name__ == '__main__':
root = Tk()
test_app = Example()
root.mainloop()
Let me know if you have any questions about the above code.