Typo
Typo

Reputation: 51

How can I get the data from all entries?

I wrote a def to create an n*n matrix with entries. I want to get the inputed data from all of the entries but I always got only the last one.

from tkinter import *

import numpy as np

root = Tk()
root.geometry('800x300')
root.title('PythonExamples.org - Tkinter Example')

global e1
global numm
global my_entry
entries=[]
my_entry= Entry(root)
e1=Entry(root)
e1.place(x=200,y=100)



def create():
    numm=int(e1.get())
    global my_entry
    for x in range(numm):
        for i in range(numm):
            my_entry = Entry(root)
            my_entry.grid(row=x, column=i)
            entries.append(my_entry)

def save():
    for entry in entries:
        my_array=entry.get()
    print(my_array)






create= Button(root,text='Submit',command=create).place(x=40,y=180)
save= Button(root,text='Save',command=save).place(x=40,y=210)

my_label=Label(root,text='')
root.mainloop()

How can I solve it? Thanks in advance.

Upvotes: 0

Views: 95

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386382

Your save function loops over the list of entry widgets, but throws away every value but the last. If you want to print out each value, move the print statement inside the loop. If you want to create an array with all of the values, append each value to a list.

def save():
    my_array = []
    for entry in entries:
        my_array.append(entry.get())
    print(my_array)

Though, that loop can be condensed into a list comprehension:

def save():
    my_array = [entry.get() for entry in entries]
    print(my_array)

Upvotes: 1

Related Questions