Home > Enterprise >  Tkinter only appending last element
Tkinter only appending last element

Time:02-07

I am inexperienced with tkinter and have been searching for a solution to this question.

This part of page1 in which a user enters an integer, which is used to generate entry boxes on another page via button:

# Towers
lbl_gt = Label(top, text="How many towers?", fg='black', font=("Helvetica", 10))
lbl_gt.place(x=420, y=280)

gt = Entry(top, width=20)
gt.focus_set()
gt.place(x=420, y=300)

On page 2 are Entry boxes in which the user types one number. I want to be able to click the OK button on this page and print the numbers that were typed in the Entry boxes. So far when I click OK, it prints only the final element in the list. For example, when I enter 1 then 2, it prints only ['2']. I want it to print ['1', '2'].

This is page2:

def gt_geo():
    top = Toplevel()
    top.title("Guard Tower Geos")
    top.geometry("200x400")

    num_gt = int(gt.get())
    GEOs = []
    for i in range(num_gt):
        gt_geo = Entry(top, width=20)
        gt_geo.focus_set()
        gt_geo.pack(side=TOP, pady=6)

    def ok():
        GEOs.append(gt_geo.get())
        print(GEOs)

    button = Button(top, text="OK", command=ok)
    button.place(x=20, y=300)

    top.mainloop()

gt_button = Button(top, text="Enter GT GEOs", command=gt_geo)
gt_button.place(x=550, y=300)

CodePudding user response:

Thank you for your comments. This worked:

        for i in range(num_gt):
        gt_geo = Entry(top, width=20)
        gt_geo.focus_set()
        gt_geo.pack(side=TOP, pady=6)
        GEOs.append(gt_geo)

    def ok():
        GEOs2 = []
        **for j in GEOs:
            GEOs2.append(j.get())**
        print(GEOs2)
  •  Tags:  
  • Related