How to add multiple entries in tkinter?

I am extremely new to Tkinter. I have been trying to create something that basically calculates the average of the marks inputted. I am trying to give the user the option to choose the number of subjects, and accordingly create that many entries.

from tkinter import *
root = Tk()
x, y, d = 0, 0, {}
for i in range(1, int(input('Enter no of subjects')) + 1):
    sub1 = Entry(root, width=15, borderwidth=5)
    sub1.grid(row=x, column=y)
    max1 = Entry(root, width=15, borderwidth=5)
    max1.grid(row=x, column=y+2)
    sub1label = Label(root, text='Marks attained', bg='grey', fg='white')
    sub1label.grid(row=x, column=y+1)
    max_sub1label = Label(root, text='Max Marks', bg='grey', fg='white')
    max_sub1label.grid(row=x, column=y+3)
    x += 1

root.mainloop()

Is there a way to store the data inputted each time so as to compute the percentage acquired? Or is there another method I can use?

Upvotes: 0

Views: 627

Answers (1)

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

You can store the values in the list and then index the list later on with the required value and get the items you wants. Here is your corrected code:

from tkinter import *

root = Tk()

def show():
    for i in range(tot_sub): # Loop through the number of subjects
        attained = attained_marks[i].get() # Get the indexed item from the list and use get()
        max_mark = max_marks[i].get()
        print(f'Attained marks: {attained}, Max marks: {max_mark}') # Print the values out

attained_marks = [] # Empty list to populate later
max_marks = [] # Empty list to populate later
tot_sub = int(input('Enter no. of subjects: ')) # Number of subjects
for i in range(tot_sub):
    sub1 = Entry(root, width=15, borderwidth=5)
    sub1.grid(row=i, column=0)
    attained_marks.append(sub1) # Append each entry to the list

    max1 = Entry(root, width=15, borderwidth=5)
    max1.grid(row=i, column=2)
    max_marks.append(sub1) # Append each entry to the list
    
    sub1label = Label(root, text='Marks attained', bg='grey', fg='white')
    sub1label.grid(row=i, column=1, padx=5)
    
    max_sub1label = Label(root, text='Max Marks', bg='grey', fg='white')
    max_sub1label.grid(row=i, column=3, padx=5)

root.bind('<Return>',lambda e: show()) # For demonstration of getting all the data

root.mainloop()

I have also changed the loop a bit as you don't need to initialize x,y,d and so on, as it can be easily achieved from inside the loop itself. I have also expanded the code so you can understand easily. Also I dont recommend using input() as it is for the terminal, use an Entry instead.

Alternatively: You can also use a dict and avoid the use of 2 lists, the dictionary would be something like {'Alternative Marks':[att1,att2,...],'Maximum Mark':[max1,max2,...]}, but this would make looping through and indexing a bit more lengthy.

Upvotes: 1

Related Questions