Why is this data not saving to the file in a correct format?

Question:
I have written a program for an assignment which is meant to allow the user to save some data which is written to a file however all that is outputted on the file is an empty “Gender :” on the file. I think it has something to do with the fact only one button survives over the iterations but i dont understand how i can fix it. Any help would be greatly appreciated
Repl link:
https://replit.com/@AceMalink45/WastefulFrozenFact#main.py

x = 1
y = 0

entryboxNames = ["First Name", "Last Name", "School Name", "Guardian Name", "Gender"]

for i in range(5):
    Label(text = entryboxNames[i]).grid(row = x, column = y)
    ent = Entry()
    Entry().grid(row = x, column = y + 1)
    x = x + 1
def save():
    with open("details.txt", "w") as file:
        file.write(entryboxNames[i] + ":" + ent.get() + "\n")
    messagebox.showinfo("Saved", "Data saved")

Thank you.

You are creating two Entry widgets in each iteration of the loop but only displaying one without assigning it to any variable.

So, you cannot access the data entered in these entry fields later in the save function.

The variable i in the save function refers to the last value it had in the loop, which is 4 in this case (for “Gender”). This is why you only see “Gender:” in your output file.

from tkinter import *
from tkinter import messagebox

addPupil = Tk()
addPupil.geometry("275x250") 
addPupil.title("Add Pupil")

Label(text="Add New Pupil", width=30).grid(columnspan=3)

entryboxNames = ["First Name", "Last Name", "School Name", "Guardian Name", "Gender"]
entries = {}  # So I'd suggest to create a dictionary to store entry widgets

for index, name in enumerate(entryboxNames):
    Label(text=name).grid(row=index + 1, column=0)
    entry = Entry(addPupil)
    entry.grid(row=index + 1, column=1)
    entries[name] = entry  # And then you need to store entry widgets in the dictionary

def save():
    with open("details.txt", "w") as file:
        for name in entryboxNames:
            file.write(name + ": " + entries[name].get() + "\n")
    messagebox.showinfo("Saved", "Data saved")

Button(text="Save", command=save).grid(row=len(entryboxNames) + 1, column=0)

addPupil.mainloop()
5 Likes

OK i understand kind of now thank you

1 Like

If i wanted to add a check to see if the user has entered any numbers how would i implement that?

You can use the str.isdigit() method

Example:

def save():
    for name, entry in entries.items():
        if any(char.isdigit() for char in entry.get()):
            messagebox.showerror("Invalid Input", f"No numbers allowed in {name}.")
            return
4 Likes

ok thank you, final question: how would i make a presence check on a singular field?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.