简体   繁体   中英

Taking user stopwatch times from a GUI and writing them to a text file that opens up with the program

Alright, I apologize but I'm completely new to python and I'm using a GUI for the first time. I currently have a GUI stopwatch program using Tkinter and need to somehow save those user inputs and write them to a text file that opens back up with the program. This is my code:

import tkinter as tink
count = -1
run = False
def var_name(stopwatch):
   def value():
      if run:
         global count
         # Just beore starting
         if count == -1:
            show = "Starting"
         else:
            show = str(count)
         stopwatch['text'] = show
         #Increment the count after every 1 second
         stopwatch.after(1000, value)
         count += 1
   value()

# While Running
def Start(stopwatch):
   global run
   run = True
   var_name(stopwatch)
   start['state'] = 'disabled'
   stop['state'] = 'normal'
   reset['state'] = 'normal'

# While stopped
def Stop():
   global run
   start['state'] = 'normal'
   stop['state'] = 'disabled'
   reset['state'] = 'normal'
   run = False

# For Reset
def Reset(label):
   global count
   count = -1
   if run == False:
      reset['state'] = 'disabled'
      stopwatch['text'] = 'Welcome'
   else:
      stopwatch['text'] = 'Start'

base = tink.Tk()
base.title("Alyssa's Stopwatch")
base.minsize(width=300, height=200,)
stopwatch = tink.Label(base, text="Let's begin!", fg="#ff5ca5", font="Times 25
bold",bg="white")
stopwatch.pack()
start = tink.Button(base, text='Start',fg="#c978ff",width=25, command=lambda:
Start(stopwatch))
stop = tink.Button(base, text='Stop', fg="#78b0ff", width=25, state='disabled',
command=Stop)
reset = tink.Button(base, text='Reset', fg="#92fcbb",width=25, state='disabled',
command=lambda: Reset(stopwatch))
start.pack()
stop.pack()
reset.pack()
base.mainloop()

There does not seem to be any read method in the code to read user input. The GUI stopwatch has "Start", "Stop", and "Reset" buttons, but no option to read user input.

Thus, it is unclear as to what user input you are referencing here:

I currently have a GUI stopwatch program using Tkinter and need to somehow save those user inputs and write them to a text file that opens back up with the program.

EDIT============================================================================

Hello.

You have to create a text file for this.

First, you create a blank text file using the open method. Have the application read in the file, and enable a writing option simultaneously. For demonstration, a "mycount.txt" file has been created in the notebook that was being worked in. An "import os" statement must be included. Open the file within the application with os.startfile("mycount.txt") and then enable the writing option.

Within the Stop() method, open the text file as a file object. Move the read cursor to the start of the file, and if the file is not empty, then go to a new line within the document. Append the observed values at the end of the file. The numbers from the stopwatch will be displayed in a text file after closing the stopwatch and then running the application again.

The code below demonstrates the process:

import tkinter as tink
import os

os.startfile("mycount.txt")
count = -1
#second_count = 0
f = open("mycount.txt","r+")

#if f.read()
#os.startfile("mycount.txt")

print(f.read())
run = False
def var_name(stopwatch):
   def value():    
      if run:
         global count
         # Just beore starting
         if count == -1:
            show = "Starting"
         else:
            show = str(count)
         stopwatch['text'] = show
         #Increment the count after every 1 second
         stopwatch.after(1000, value)


         count += 1


   value()

# While Running
def Start(stopwatch):
   global run
   run = True
   var_name(stopwatch)
   start['state'] = 'disabled'
   stop['state'] = 'normal'
   reset['state'] = 'normal'

# While stopped
def Stop():
   global run
   start['state'] = 'normal'
   stop['state'] = 'disabled'
   reset['state'] = 'normal'
   run = False


   with open("mycount.txt","a+") as file_object:
       #Move Read cursor to the start of the file.
       file_object.seek(0)
       #If file is not empty, then append "\n"

       data = file_object.read(100)
       if len(data) > 0:
            file_object.write("\n")
        #Append text at the end of the file

       f.write(str(count-1) + "\n")
       print(f.read())
       f.close()




# For Reset
def Reset(label):
   global count
   count = -1
   if run == False:
      reset['state'] = 'disabled'
      stopwatch['text'] = 'Welcome'
   else:
      stopwatch['text'] = 'Start'

base = tink.Tk()
base.title("Alyssa's Stopwatch")
base.minsize(width=300, height=200,)
stopwatch = tink.Label(base, text="Let's begin!", fg="#ff5ca5", font="Times 25 bold",bg="white")
stopwatch.pack()
start = tink.Button(base, text='Start',fg="#c978ff",width=25, command=lambda:Start(stopwatch))
stop = tink.Button(base, text='Stop', fg="#78b0ff", width=25, state='disabled',command=Stop)
reset = tink.Button(base, text='Reset', fg="#92fcbb",width=25, state='disabled',command=lambda: Reset(stopwatch))
start.pack()
stop.pack()
reset.pack()
base.mainloop()

Hope this helps!

tkinter doesn't have special functions to read and write config so you have to do it on your own. Use standard open() , read() , write() , close() or modules to keep it in file JSON , YAML or .ini . You will have to read config before Tk() (if you want to use confing to create windgets) or before mainloop() (if you want to change existing widgets) and save it after mainloop() (or when you change state)


I use JSON to keep config because it is standard module (so you don't have to install it) and it converts text with number to integer/float value, text "false/true" to boolean value False/True , etc. (so it will need less work/code)

Read:

    with open('config.txt') as fh:
        config = json.load(fh)

    count = config['count']
    run = config['run']

Save:

    config = { 
        'count': count,
        'run': run,
    }

    with open('config.txt', 'w') as fh:
        json.dump(config, fh)

Because after getting config from file I also want to update text on label and buttons so I read config after creating all widgets.

# read after creating widgets because config updates text on label and buttons
load_config()

base.mainloop()

# save after closing window
save_config()

Full code with other changes

PEP 8 -- Style Guide for Python Code

import json
import tkinter as tk

# --- functions ---

def update():
    global count # PEP8: all `global` at the beginning to make it more readable

    if run:
       # just before starting
       if count == -1:
          show = "Starting"
       else:
          show = count
       stopwatch['text'] = show # there is no need to use `str()`

       # increment the count after every 1 second
       count += 1

       stopwatch.after(1000, update)


# while running
def on_start(): # PEP8: lower_case_names for functions
   global run

   run = True

   start['state'] = 'disabled'
   stop['state'] = 'normal'
   reset['state'] = 'normal'

   update()


# while stopped
def on_stop(): # PEP8: lower_case_names for functions
   global run

   run = False

   start['state'] = 'normal'
   stop['state'] = 'disabled'
   reset['state'] = 'normal'


# for reset
def on_reset(): # PEP8: lower_case_names for functions
   global count

   count = -1
   #if run == False:
   #if run is False: # PEP8: `is False` instead `== False`
   if not run:  # PEP8: more preferred then `is False` (and you can read it like English text)
      reset['state'] = 'disabled'
      stopwatch['text'] = 'Welcome'
   else:
      stopwatch['text'] = 'Start'


def load_config():
    global count
    global run

    try:
        with open('config.txt') as fh:
            config = json.load(fh)

        print('[DEBUG] load_config:', config)

        count = config['count']
        run = config['run']

        # update label and buttons
        if count > -1:
            # update text on label
            stopwatch['text'] = count
            # continue counting and/or update text on buttons
            if run:
                on_start()
            else:
                on_stop()
    except Exception as ex:
        # if there is empty/broken config file (or it doesn't exist yet)
        print('Exception:', ex)

def save_config():
    # create data to save
    config = { 
        'count': count,
        'run': run,
    }

    print('[DEBUG] save_config:', config)

    with open('config.txt', 'w') as fh:
        json.dump(config, fh)

# --- main ---

count = -1
run = False

base = tk.Tk()
base.title("Alyssa's Stopwatch")
base.minsize(width=300, height=200,)

stopwatch = tk.Label(base, text="Let's begin!",
                     fg="#ff5ca5", font="Times 25 bold", bg="white")
stopwatch.pack()

start = tk.Button(base, text='Start',
                  fg="#c978ff", width=25, command=on_start)
stop = tk.Button(base, text='Stop',
                 fg="#78b0ff", width=25, state='disabled', command=on_stop)
reset = tk.Button(base, text='Reset',
                  fg="#92fcbb", width=25, state='disabled', command=on_reset)
start.pack()
stop.pack()
reset.pack()

# read after creating widgets because config updates text on label and buttons
load_config()

base.mainloop()

# save after closing window
save_config()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM