1

I'm trying to make a Student Information System, the information will be stored in a text file, and will be shown through a table.

Submit button function:

def submit():
    if idEntry.get() == "" or nameEntry.get() == "" or yearEntry.get() == "" or courseEntry.get() == "":
        messagebox.showerror("ERROR", "Student information can't be left in a blank!")
        return
    if not idEntry.get().isdigit():
        messagebox.showerror("ERROR", "Student ID number must be a digit!")
        return
    elif not yearEntry.get().isdigit():
        messagebox.showerror("ERROR", "Student year must be a digit!")
        return
    with open("sis.txt", "a") as f:
        f.write(f"{idEntry.get()},{nameEntry.get()},{yearEntry.get()},{courseEntry.get()}\n")
        f.close
    messagebox.showinfo("Successful", "Student is enrolled")
    student = [idEntry.get(),nameEntry.get(),yearEntry.get(),courseEntry.get()]
    table.insert(parent='',index=0,values=student)

Table:

table = ttk.Treeview(window, columns=('idnum','name','year','course'), show='headings')
table.heading('idnum', text='ID Number')
table.heading('name', text='Name')
table.heading('year', text='Year')
table.heading('course', text='Course')
table.pack(fill='both',expand=True,padx=10,pady=10)


table.bind('<<TreeviewSelect>>', item_select)

with open("sis.txt", "r") as f:
    for line in f:
        data = line.strip().split(",")
        student = (data[0],data[1],data[2],data[3])
        table.insert(parent='',index=0,values=student)

I have tried:

with open("sis.txt", "a") as f:
        for stdnt in table:
            if idEntry.get() == stdnt:
                messagebox.showerror("ERROR", "You can't use the same ID number!")
                return

And:

for stndt in table.item():
        if idEntry.get() == stndt:
            messagebox.showerror("ERROR", "You can't use the same ID number!")
        print(stndt)
5
  • 4
    minimal reproducible example ; it's not clear what you try to achieve and how your approach didn't work for you; e.g. undefined *Entry, messagebox Commented Oct 22 at 12:29
  • 1
    Easy, don't ask them for the ID. If it's a new student, you assign them a unique id. Commented Oct 22 at 12:32
  • you are iterating over the table incorrectly. you can use the get_children method to get the Tkinter ID of all the rows in the table. You can then iterate over the rows and get the currently existing student IDs, and check if the new student ID clashes with any of them. Commented Oct 22 at 12:36
  • 1
    Suggest to use SQLite DB instead of a text file to store those records. It is more easier to check uniqueness of ID. Commented Oct 22 at 13:32
  • Where is table/your data ultimately being stored? Commented Oct 22 at 18:01

2 Answers 2

2

You need to use table.get_children() to get all the row IDs in table and use table.set() to get the student ID in each row to check whether the input student ID exists:

def submit():
    sid = idEntry.get().strip()
    name = nameEntry.get().strip()
    year = yearEntry.get().strip()
    course = courseEntry.get().strip()

    if sid == "" or name == "" or year == "" or course == "":
        messagebox.showerror("ERROR", "Student information can't be left in a blank!")
        return
    if not sid.isdigit():
        messagebox.showerror("ERROR", "Student ID number must be a digit!")
        return
    elif not year.isdigit():
        messagebox.showerror("ERROR", "Student year must be a digit!")
        return

    # check whether input student ID exists in the table
    for row in table.get_children():
        if sid == table.set(row, 'idnum'):
            messagebox.showerror("ERROR", "You can't use the same ID number!")
            return

    with open("sis.txt", "a") as f:
        f.write(f"{sid},{name},{year},{course}\n")
        #f.close does not call the function
        # and it is not necessary at all when using with statement
        
    messagebox.showinfo("Successful", "Student is enrolled")
    student = [sid, name, year, course]
    table.insert(parent='', index=0, values=student)
Sign up to request clarification or add additional context in comments.

Comments

1

Hi and welcome to Stack Overflow!

First of all you want to manage the stored data somehow. In GUI applications you usually want to have a separate visual component, data model, and in your case also a permanent storage, or a database (in your case 'sis.txt').

I personally would probably first define a container of students, e.g. a list or a dict of students. Next I'd write a function save(filepath: str, students: dict) which takes this container and output filename as argument and always rewrites (hence updates) our database.

Similarly I'd write a load(filepath): dict function which takes the same filename where the students are stored, and returns the student container. This should give you an identical student container.

So now you've implemented your the data handling part. Next, somewhere in the code, e.g. where you already check for valid conditions, you also check for the id.

E.g. function to check only the ID:

def is_id_unique(new_id: int, filepath: str) -> bool:
    students = load(filepath)

    # Search for new_id in students:
    for student in students:
        if int(student["id"]) == new_id:
            return False  # Identical ID found, return false immediately
    return True  # All students checked and no identical ID was found, return true

In your existing submit() function:

def submit():
    # ... beginning of your function
    elif not yearEntry.get().isdigit():
        messagebox.showerror("ERROR", "Student year must be a digit!")
        return

    elif not is_id_unique(int(idEntry.get()):
        messagebox.showerror("ERROR", "ID already exists")
        return

    with open("sis.txt", "a") as f:
    # ... rest of your function

Also, as @Kenny-Ostrom suggested, in real-world examples the server generates a new, not yet existing ID. However here the program also needs to know which IDs were assigned already. Many more improvements would be recommended but this was not a part of the question.

2 Comments

Hello, thank you for responding to my question. I have been learning python for 2 months in college. A part of my code being shown is for a final project of this trimester, which requires me to use a .txt file to store the data. Tkinter is newly taught this week, so apologies if I have plenty of follow-up questions regarding your response. I am not familiar with the syntax "load()", when the running the code provided, an error would occur after pressing the submit button, which states that "load" is not defined and it is giving emphasis on is_id_unique(int(idEntry.get()),"sis.txt"): and load.
Hi sorry for not being clear... When I told I'd write "load()"/"save()" function, I meant I would define such functions. Basically "load" the part of your code where you open and read the file, and "save" where you write to the file. The functions are not necessary but they help to abstract out the parts of your code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.