I will appreciate any help. I got stuck with hours to find the solution.
import tkinter as tk
import time
import datetime
from tkinter import Frame
from tkinter import *
import csv
class StopWatch(Frame):
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw)
self._start = 0.0
self._elapsedtime = 0.0
self._running = 0
self.timestr = StringVar()
self.makeWidgets()
def makeWidgets(self):
""" Make the time label. """
self.time_label = Label(self, textvariable=self.timestr)
self._setTime(self._elapsedtime)
self.time_label.pack(fill=X, expand=NO, pady=2, padx=2)
def _update(self):
""" Update the label with elapsed time. """
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._timer = self.after(50, self._update)
def _setTime(self, elap):
""" Set the time string to Minutes:Seconds:Hundreths """
minutes = int(elap/60)
seconds = int(elap - minutes*60.0)
hseconds = int((elap - minutes*60.0 - seconds)*100)
self.time_label.configure(text='%02d:%02d:%02d' % (minutes, seconds, hseconds))
def Start(self):
""" Start the stopwatch, ignore if running. """
if not self._running:
self._start = time.time() - self._elapsedtime
self._update()
self._running = 1
def Stop(self):
""" Stop the stopwatch, ignore if stopped. """
if self._running:
self.after_cancel(self._timer)
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._running = 0
def Reset(self):
""" Reset the stopwatch. """
self._start = time.time()
self._elapsedtime = 0.0
self._setTime(self._elapsedtime)
def clock_in(self):
global e1
data = e1.get()
ClockIn_time = datetime.datetime.now()
ClockIn_date = datetime.datetime.now().strftime('%Y-%m-%d')
totalinput = [ data, ClockIn_time, ClockIn_date]
with open(self.filename, "a") as savedb:
w = csv.writer(savedb)
w.writerow(totalinput)
def clock_out(self):
global e1
data = e1.get()
ClockOut_time = datetime.datetime.now()
ClockOut_date = datetime.datetime.now().strftime('%Y-%m-%d')
totalinput = [ data, ClockOut_time , ClockOut_date ]
with open(self.filename, "a") as savedb:
w = csv.writer(savedb)
w.writerow(totalinput)
def main():
global e1
root = Tk()
sw = StopWatch(root)
sw.pack(side=TOP)
root.geometry("400x400")
####
label = tk.Label(root, text="Employee Name: ")
label.pack(side="top")
new = StringVar()
e1 = Entry(root, textvariable=new)
e1.pack()
#######
btn1 = Button(root, text='Clock In', command=lambda :[sw.Start(), sw.clock_in()])
btn1.pack(side=LEFT)
btn2 = Button(root, text='Clock Out', command=lambda :[sw.Start(), sw.clock_out()])
btn2.pack(side=LEFT)
btn3 = Button(root, text='Reset', command=sw.Reset)
btn3.pack(side=LEFT)
btn4 = Button(root, text='Quit', command=root.quit)
btn4.pack(side=LEFT)
root.mainloop()
if __name__ == '__main__':
main()
