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



好吧,我很抱歉,但我对python完全陌生,而且我是第一次使用GUI。我目前有一个使用Tkinter的GUI秒表程序,需要以某种方式保存这些用户输入,并将它们写入一个文本文件,该文件将随程序一起打开。这是我的代码:

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

代码中似乎没有任何读取方法来读取用户输入。GUI秒表有"开始"、"停止"one_answers"重置"按钮,但没有读取用户输入的选项。

因此,不清楚您在这里引用的是什么用户输入:

我目前有一个使用Tkinter的GUI秒表程序,需要以某种方式保存这些用户输入,并将其写入一个文本文件,该文件将随程序一起打开

编辑================================================

你好。

您必须为此创建一个文本文件。

首先,使用open方法创建一个空白文本文件。在文件中读取应用程序,并启用写入选项。为了进行演示,可以使用一个"mycount.txt"文件已在正在处理的笔记本中创建必须包含"import-os"语句。在使用os.startfile("mycount.txt"(的应用程序,然后启用写入选项。

在Stop((方法中,将文本文件作为文件对象打开。将读取光标移到文件的开头,如果文件不是空的,则转到新的行。将观察到的值附加到文件末尾。关闭秒表并再次运行应用程序后,秒表中的数字将显示在文本文件中。

下面的代码演示了这个过程:

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

希望这能有所帮助!

tkinter没有读取和写入配置的特殊功能,因此您必须自己完成。使用标准open()read()write()close()或模块将其保存在文件JSONYAML.ini中。您必须在Tk()(如果您想使用confing创建windgets(或mainloop()(如果您想要更改现有的小部件(之前读取配置,并在mainloop()(或当您更改状态时(之后保存


我使用JSON来保持配置,因为它是标准模块(所以你不必安装它(,它将带数字的文本转换为整数/浮点值,将文本"false/true"转换为布尔值False/True等(所以它需要更少的工作/代码(

读取:

with open('config.txt') as fh:
config = json.load(fh)
count = config['count']
run = config['run']

保存:

config = { 
'count': count,
'run': run,
}
with open('config.txt', 'w') as fh:
json.dump(config, fh)

因为从文件中获取配置后,我还想更新标签和按钮上的文本,所以我在创建所有小部件后读取配置。

# read after creating widgets because config updates text on label and buttons
load_config()
base.mainloop()
# save after closing window
save_config()

完整代码和其他更改

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

最新更新