Getting the value of an entry

I have a function that creates me a label and and entry

#creates an entry
def create_entry(l_text,l_col, e_size,data_name):
    l_name=ttk.Label(data_frame,text=l_text, justify="left", width=len(l_text))    # create a label first
    l_name.grid(row=row_nr,column=l_col,padx=pad_x,pady=pad_y)		                # define position
    e_name=ttk.Entry(data_frame,width=e_size,justify="left")						# create the entry
    e_name.grid(row=row_nr,column=l_col+1,padx=pad_x,pady=pad_y)		             # define position
    data_name = e_name.get()											         # add e_name to list

I call it i.e.

create_entry("CA_NAME",0,10,CA)

CA is defined CA = “”

My intention is to simplify creting multiple entry fieeds. that works fine so long. with the parameter “data_name” I like to pass a the name of a vaiable the entry value should be stored, but is alwasy empty. How can I update it when entering data in the filed or modify the value in the field

Thank you for any help or hint

This should read;

e_name=ttk.Entry(data_frame,width=e_size,justify="left",textvariable=data_name)

The value of textvariable than reflects the input and you can programmatically change it too.

This gives you the value of the content of the field once, at the moment it is executed, so immediately after creating it.

CA is a variable that contains the value "" initially.

You’re passing the value of CA, i.e. "", into create_entry, and that value is being assigned to a local variable called data_name.

At the end of the function, you’re getting the contents of the entry widget, and assigning it to local variable data_name, replacing its existing value.

Because you’ve only just created the entry widget, it’ll be empty, so the value assigned will also be "", but that doesn’t really matter because data_name is a local variable that’ll go away when the function returns.

Also, because you assigned the reference to the entry widget in e_name, which is a local variable, you won’t have a way to get the contents of the widget later on, after the function returns.

I recommend you use a tkinter StringVar, something like this:

#creates an entry
def create_entry(l_text, l_col, e_size, text_var):
    l_name = ttk.Label(data_frame, text=l_text, justify="left", width=len(l_text))      # create a label first
    l_name.grid(row=row_nr, column=l_col, padx=pad_x, pady=pad_y)		                # define position
    e_name = ttk.Entry(data_frame, width=e_size, justify="left", textvariable=text_var) # create the entry
    e_name.grid(row=row_nr, column=l_col+1, padx=pad_x, pady=pad_y)		                # define position

# create a tkinter variable to bind to the entry widget
CA_var =  tk.StringVar()
create_entry("CA_NAME", 0, 10, CA_var)

You can then use CA_var.get() to get the contents of the entry widget or CA_var.set(some_value) to change its contents.

1 Like

Hello,

You can potentially do this by way of the following example. If it is not exactly what you are looking for, there are some Pythonic techniques that you can use such as for loops, list comprehensions, and list/zip pairs that can simplify your scripting. The idea is to pass in the desired entries via a list and the script will format the entries onto the window for you.
This way, you don’t have to create an entry one by one manually every time that you’d like to add one. The script works under the assumption that you already have a predefined list of entries that you would like to create.

import tkinter as tk

class App(tk.Tk):

    def __init__(self, fields):

        super().__init__()

        self.fields = fields
        labels = [tk.Label(self, text=f) for f in self.fields]

        entry_fields = []
        entries = []

        # Create variables for entries
        for i in range(len(self.fields)):
            entry_fields.append(tk.StringVar())

        # Create widget entries with string variable assignments
        for index in range(len(self.fields)):
            entries.append(tk.Entry(self, textvariable=entry_fields[index]))

        # Create association between labels and entries
        self.widgets = list(zip(labels, entries))

        # Create the button and configure the associated method to call
        # when button is pressed
        self.submit = tk.Button(self, text="Print info", command = self.print_info)

        # Put the entries and labels onto the window
        for i, (label, entry) in enumerate(self.widgets):

            label.grid(row=i, column=0, padx=10, sticky=tk.W)
            entry.grid(row=i, column=1, padx=10, pady=5)
            self.submit.grid(row=len(fields), column=1, sticky=tk.E,
                             padx=10, pady=10)

    def print_info(self, *args):

        for label, entry in self.widgets:
            print('{:<12} {:>25}'.format(label.cget("text")+':', entry.get()))

if __name__ == "__main__":

    # Create instance by passing in the desired entry list
    app = App(["First Name", "Last Name", "Phone", "Email"])
    app.mainloop()

I have gone ahead and commented most of the script to guide you as to what each sub-script is doing.

1 Like

Thank you for your help
Your solution works well for me and I have not very much change