简体   繁体   English

从 GUI 获取用户秒表时间并将其写入由程序打开的文本文件

[英]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.好吧,我很抱歉,但我对 python 完全陌生,而且我是第一次使用 GUI。 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.我目前有一个使用 Tkinter 的 GUI 秒表程序,需要以某种方式保存这些用户输入并将它们写入一个文本文件,该文本文件可以用该程序打开备份。 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. GUI 秒表具有“开始”、“停止”和“重置”按钮,但没有读取用户输入的选项。

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.我目前有一个使用 Tkinter 的 GUI 秒表程序,需要以某种方式保存这些用户输入并将它们写入一个文本文件,该文本文件可以用该程序打开备份。

EDIT============================================================================编辑================================================== ============================

Hello.你好。

You have to create a text file for this.您必须为此创建一个文本文件。

First, you create a blank text file using the open method.首先,您使用 open 方法创建一个空白文本文件。 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.为了演示,在正在使用的笔记本中创建了一个“mycount.txt”文件。必须包含一个“import os”语句。 Open the file within the application with os.startfile("mycount.txt") and then enable the writing option.使用 os.startfile("mycount.txt") 在应用程序中打开文件,然后启用写入选项。

Within the Stop() method, open the text file as a file object.在 Stop() 方法中,将文本文件作为文件 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.将读取的 cursor 移动到文件的开头,如果文件不为空,则 go 到文件内的新行。 Append the observed values at the end of the file. Append 文件末尾的观测值。 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. tkinter没有读取和写入配置的特殊功能,因此您必须自己完成。 Use standard open() , read() , write() , close() or modules to keep it in file JSON , YAML or .ini .使用标准open()read()write()close()或模块将其保存在文件JSONYAML.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)您必须在Tk()之前(如果您想使用 confing 创建windgets)或在mainloop()之前(如果您想更改现有小部件)阅读配置,并在mainloop()之后(或更改状态时)保存它


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)我使用JSON来保留配置,因为它是标准模块(因此您不必安装它),它将带有数字的文本转换为整数/浮点值,将文本“false/true”转换为 boolean 值False/True等(所以它需要更少的工作/代码)

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.因为从文件中获取配置后,我还想更新 label 和按钮上的文本,所以我在创建所有小部件后读取配置。

# 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 PEP 8 -- Python 代码的样式指南

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 提取根据多个文本文件中的数据计算得出的输出,并将其写入CSV文件的不同列 - Taking output calculated from data in multiple text files and writing them into different columns of a CSV file 将每个项目放在列表中并将其写入文本文件 - Taking each item in a list and writing them on a text file 一个打开文本文件的程序,计算单词的数量,并按照它们在文件中出现的次数报告排序的前N个单词? - A program that opens a text file, counts the number of words and reports the top N words ordered by the number of times they appear in the file? 从文本文件中获取数据并将其作为python中的.csv文件写入 - Taking data from text file and writing it as a .csv file in python 从用户获取输入并将其写入文本文件 - Getting input from user and writing it to a text file 将python程序的屏幕输出打印到文件,而无需将其写入python程序内的文件 - print out the on-screen-output from a python program to a file without writing them to a file inside the python program 通过仅拍摄一些帧而无需将它们写入文件来从另一个视频创建视频 - Create a video from another video by taking some frames only but without writing them onto a file 写入文本文件程序:从 Python 2 转换为 Python 3 - Writing to a text file program: convert from Python 2 to Python 3 如何通过从 txt 文件中获取输入名称而不是使用 args 解析器将它们写入终端来运行 python 代码文件? - How can I run python code file by taking input names from a txt file instead of writing them in terminal with args parser? 将同一件事多次写入文本文件 - Writing the same thing to a text file multiple times
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM