Python Forum
stopwatch output to txt file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
stopwatch output to txt file
#1
Hi,

I'm a Python NOOB and I have an idea of that I'm trying to do but struggling to achieve end goal. I've found code (online - can't find the URL anymore since I acquired example) and the code works fine... click START/STOP/RESET/QUIT.

I've added an APPEND to file line in the STOP button function; the idea is to capture the time in a text file. I think I may need to convert the time to a string and capture that, but I'm struggling to find an example that works for me.

I am using Python 3.6.5... code below:

try:
    # for Python2
    from Tkinter import *   ## notice capitalized T in Tkinter 
except ImportError:
    # for Python3
    from tkinter import *   ## notice lowercase 't' in tkinter here
    
import time

class StopWatch(Frame):  
    """ Implements a stop watch frame widget. """                                                                
    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. """
        l = Label(self, textvariable=self.timestr)
        self._setTime(self._elapsedtime)
        l.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.timestr.set('%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

#-------MY CODE INSERT-------------------------------------------------------------
        # save file
        
        # convert to string
            example = time
            str(example)
            repr(example)
            f = open("C:\pytest\stopwatch_test.txt","a")
            f.write(example)
            f.close()
#--------------------------------------------------------------------

    
    def Reset(self):                                  
        """ Reset the stopwatch. """
        self._start = time.time()         
        self._elapsedtime = 0.0    
        self._setTime(self._elapsedtime)
        
        
def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)
    
    Button(root, text='Start', command=sw.Start).pack(side=LEFT)
    Button(root, text='Stop', command=sw.Stop).pack(side=LEFT)
    Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
    Button(root, text='Quit', command=root.quit).pack(side=LEFT)
    
    root.mainloop()

if __name__ == '__main__':
    main()
I have tried a few things and keep coming back to self._elapsedtime & '%02d:%02d:%02d' % (minutes, seconds, hseconds))

Any help would be appreciated... in the meantime, I have just started an intro Python course on Pluralsight.com
Reply
#2
replace your insert with
            with open("C:\pytest\stopwatch_test.txt","a") as f:
                f.write(time.ctime())
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Hi buran,
Thank you for your prompt reply and suggestion.
I tried your code and it writes the 'system-time/date' instead of app output :(
I'm trying to capture Minutes:Seconds:Hundreths.

Thanks,
Roberto
Reply
#4
Just write the self.timestr in your file, like @buran said.

ith open("C:\pytest\stopwatch_test.txt","a") as f:
    f.write(self.timestr)
Reply
#5
Hi gontajones,
I get error: TypeError: write() argument must be str, not StringVar

Thanks for your reply though ;)
Reply
#6
f.write(self.timestr.get())
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Thanks Buran.... that did the trick!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,046 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Output CSV file with filepath and file contents glittergirl 1 1,708 Aug-03-2020, 01:50 AM
Last Post: glittergirl
  csv file output rturus 7 3,162 Jan-30-2020, 02:09 PM
Last Post: buran
  File name as part of output file name Jeeping_Coder 1 2,080 Jan-10-2020, 03:43 PM
Last Post: Clunk_Head
  How to extract a matrix from .xml.gz file to a excel file or any other output? enyrb 0 2,029 Oct-21-2019, 01:01 PM
Last Post: enyrb
  python file output to log file Rsh 4 3,643 Aug-13-2019, 09:00 PM
Last Post: DeaD_EyE
  Output SQL to csv or xls file? JP_ROMANO 4 2,542 Aug-02-2019, 01:58 AM
Last Post: JP_ROMANO
  Imperfect Stopwatch PoetLearnsPython 1 1,531 Jul-20-2019, 05:58 PM
Last Post: ichabod801
  Error when trying to run a stopwatch nath2125 1 1,872 Feb-23-2019, 09:14 PM
Last Post: Yoriz
  Stopwatch Panda 1 2,177 Jul-11-2018, 10:21 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020