How to write an "if" statement that all Entry boxes that are not equal to 'Enter Employee Name' will be saved to a file?

Viewed 46

I am using python to make an employee name log that has 6 rows for new names to be entered. If there is no name left entered into the Entry box and it's left saying 'Enter Employee Name', I want to ignore it and not write it to a file.

Currently the way I have things it just prints if the condition is met and it kind of works but seems long. Is there a way to not include an Entry variable if it's not equal to 'Enter Employee Name'?

from tkinter import *
from datetime import *
import time

# define GUI
root = Tk()
root.title("Make Communication Record")
root.geometry("550x775")

# Time Stamp Label
day = datetime.today()
hour = time.strftime("%H")
minute = time.strftime("%M")
sec = time.strftime("%S")
f_daydisplay = day.strftime("%A - %B %d, %Y ")
t = f_daydisplay + " " + hour + ":" + minute + ":" + sec

#Refresh clock for time stamp label
def clock():
    day = datetime.today()
    f_daydisplay = day.strftime("%A - %B %d, %Y at ")
    hour = time.strftime("%H")
    minute = time.strftime("%M")
    sec = time.strftime("%S")

    timelab.config(text=f_daydisplay+hour + ":" + minute + ":" + sec)
    timelab.after(1000, clock)

#Time stamp label 
timelab = Label(root, text="")
timelab.grid(row=13, columnspan=4)
clock()

# Button Actions
def onclick(args):

    # If submit clicked
    if args == 1:
        one = nameone.get()
        two = nametwo.get()
        three = namethree.get()
        four = namefour.get()
        five = namefive.get()
        six = namesix.get()

        if (one != 'Enter Employee Name' and two != 'Enter Employee Name' and three != 'Enter Employee Name' and four != 'Enter Employee Name' and five != 'Enter Employee Name' and six != 'Enter Employee Name'):
            print('it worked all')
        elif(one != 'Enter Employee Name' and two != 'Enter Employee Name' and three != 'Enter Employee Name' and four != 'Enter Employee Name' and five != 'Enter Employee Name'):
            print('it worked 4')
        elif(one != 'Enter Employee Name' and two != 'Enter Employee Name' and three != 'Enter Employee Name' and four != 'Enter Employee Name'):
            print('it worked 3')
        elif(one != 'Enter Employee Name' and two != 'Enter Employee Name' and three != 'Enter Employee Name'):
            print('it worked 2')
        elif(one != 'Enter Employee Name' and two != 'Enter Employee Name'):
            print('it worked 1')
        elif(str(one) != 'Enter Employee Name'):
            print('it worked 0')

    # if reset button clicked
    if args == 2:
        namea.insert(0, 'Enter Employee Name')
        nameb.insert(0, 'Enter Employee Name')
        namec.insert(0, 'Enter Employee Name')
        named.insert(0, 'Enter Employee Name')
        namee.insert(0, 'Enter Employee Name')
        namef.insert(0, 'Enter Employee Name')

# Name Entry
nameone = StringVar()
namea = Entry(root, width=30, borderwidth=5, textvariable=nameone)
namea.grid(row=2, column=0, columnspan=1, padx=10, pady=10)
namea.insert(0, "Enter Employee Name")

nametwo = StringVar()
nameb = Entry(root, width=30, borderwidth=5, textvariable=nametwo)
nameb.grid(row=3, column=0, columnspan=1, padx=10, pady=10)
nameb.insert(0, "Enter Employee Name")

namethree = StringVar()
namec = Entry(root, width=30, borderwidth=5, textvariable=namethree)
namec.grid(row=4, column=0, columnspan=1, padx=10, pady=10)
namec.insert(0, "Enter Employee Name")

namefour = StringVar()
named = Entry(root, width=30, borderwidth=5, textvariable=namefour)
named.grid(row=5, column=0, columnspan=1, padx=10, pady=10)
named.insert(0, "Enter Employee Name")

namefive = StringVar()
namee = Entry(root, width=30, borderwidth=5, textvariable=namefive)
namee.grid(row=6, column=0, columnspan=1, padx=10, pady=10)
namee.insert(0, "Enter Employee Name")

namesix = StringVar()
namef = Entry(root, width=30, borderwidth=5, textvariable=namesix)
namef.grid(row=7, column=0, columnspan=1, padx=10, pady=10)
namef.insert(0, "Enter Employee Name")

#Buttons
btn1 = Button(root, text="Submit", width=20, command=lambda: onclick(1))
btn1.grid(row=12, column=0, padx=10, pady=10)

btn2 = Button(root, text="Reset Fields",
              width=20, command=lambda: onclick(2))
btn2.grid(row=12, column=2, padx=10, pady=10)

root.mainloop()

1 Answers

When you find yourself writing repetitive code like that, it is a strong signal of the need to start storing the things being operated-upon in some kind of container, such as a list, and then perform operations on each of its contents in a for-loop. Putting this advice into practice is an example of following the DRY or Don't repeat yourself principle of software engineering.

The code below shows how to do this: All the StringVars are stored in a name_vars list, and all the Entry widgets are in one named name_entries.

from datetime import *
import time
from tkinter import *

ENTER_EMP_NAME = 'Enter Employee Name'
NUM_EMP_NAMES = 6
EMP_LOG_FILENAME = 'emp_log.txt'

# define GUI
root = Tk()
root.title("Make Communication Record")
root.geometry("550x775")

# Time Stamp Label
day = datetime.today()
hour = time.strftime("%H")
minute = time.strftime("%M")
sec = time.strftime("%S")
f_daydisplay = day.strftime("%A - %B %d, %Y ")
t = f_daydisplay + " " + hour + ":" + minute + ":" + sec

#Refresh clock for time stamp label
def clock():
    day = datetime.today()
    f_daydisplay = day.strftime("%A - %B %d, %Y at ")
    hour = time.strftime("%H")
    minute = time.strftime("%M")
    sec = time.strftime("%S")

    timelab.config(text=f_daydisplay+hour + ":" + minute + ":" + sec)
    timelab.after(1000, clock)

#Time stamp label
timelab = Label(root, text="")
timelab.grid(row=13, columnspan=4)
clock()

# Button actions
def onclick(args):
    if args == 1:  # Submit clicked.
        names = [var.get() for var in name_vars if var.get() != ENTER_EMP_NAME]
        if not names:
            print('No names were filled in, no log file written.')
            return

        print(f'Saving {len(names)} names to file.')
        with open(EMP_LOG_FILENAME, 'w') as log_file:
            for name in names:
                log_file.write(name+'\n')
        return

    if args == 2:  # Reset button clicked.
        for entry in name_entries:
            entry.delete(0, END)  # Delete entire current contents.
            entry.insert(0, ENTER_EMP_NAME)
        return

# Name entry boxes
name_vars = []
name_entries = []
for i in range(NUM_EMP_NAMES):
    name_var = StringVar(value=ENTER_EMP_NAME)
    name_vars.append(name_var)
    name_entry = Entry(root, width=30, borderwidth=5, textvariable=name_var)
    name_entry.grid(row=i+2, column=0, columnspan=1, padx=10, pady=10)
    name_entries.append(name_entry)

# Buttons
btn1 = Button(root, text="Submit", width=20, command=lambda: onclick(1))
btn1.grid(row=12, column=0, padx=10, pady=10)

btn2 = Button(root, text="Reset Fields",  width=20, command=lambda: onclick(2))
btn2.grid(row=12, column=2, padx=10, pady=10)

root.mainloop()
Related