Search code examples
pythonpython-3.xtkintertkinter-entry

Creating a set of Entry Widgets as per the user's decision and find the average of them all with Tkinter


Goal: A Programs takes in a input from the user, as to how many Entry widgets are needed. If the user enters '5' then 5 Entry Widgets should be created, and then the user inputs 5 numbers and then the program should display the average of those numbers.

def create_entries(r):
    if r % 2 == 0:
        entry = Entry(frame)
        entry.grid(row=r,column=0,padx=2)
        return entry
    else:
        entry = Entry(frame)
        entry.grid(row=r-1,column=1,padx=2)
        return entry
List_of_entries = [create_entries(r) for r in range(user_input)]

Actually this above program creates a fixed number of entries and stores the Entry Widgets as a List. By calling List_of_entries[0].get() , I can access the value of the first text field and so no.. and so forth.. This program arranges the text fields in a matrix.This is a sub-function inside a main-function whenever Return is pressed the main-function starts.

My Problem: This program creates '5 Entry Widgets' if the user inputs '5' and then presses the Return Key and when the user clears the text field and types '4' (which is less than 5) and presses Return Button still it shows '5 instead of 4 Entry Widgets'. Please help me with my problem

Email: p.rhubanraj@gmail.com

for more information.


Solution

  • You can start by defining an empty list instead, and append to the list instead of creating by list comprehension.

    List_of_entries = []
    
    def create_entries(r):
        global List_of_entries
        for i in List_of_entries:
            i.destroy()
        List_of_entries = []
        for i in range(r):
            entry = tk.Entry(frame)
            entry.grid(row=i,column=0,padx=2)
            List_of_entries.append(entry)