![](/img/trans.png)
[英]Taking output calculated from data in multiple text files and writing them into different columns of a CSV file
[英]Taking user stopwatch times from a GUI and writing them to a text file that opens up with the program
好吧,我很抱歉,但我对 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 秒表具有“开始”、“停止”和“重置”按钮,但没有读取用户输入的选项。
因此,您在此处引用的用户输入尚不清楚:
我目前有一个使用 Tkinter 的 GUI 秒表程序,需要以某种方式保存这些用户输入并将它们写入一个文本文件,该文本文件可以用该程序打开备份。
编辑================================================== ============================
你好。
您必须为此创建一个文本文件。
首先,您使用 open 方法创建一个空白文本文件。 让应用程序读取文件,并同时启用写入选项。 为了演示,在正在使用的笔记本中创建了一个“mycount.txt”文件。必须包含一个“import os”语句。 使用 os.startfile("mycount.txt") 在应用程序中打开文件,然后启用写入选项。
在 Stop() 方法中,将文本文件作为文件 object 打开。 将读取的 cursor 移动到文件的开头,如果文件不为空,则 go 到文件内的新行。 Append 文件末尾的观测值。 关闭秒表并再次运行应用程序后,秒表中的数字将显示在文本文件中。
下面的代码演示了这个过程:
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()
或模块将其保存在文件JSON
、 YAML
或.ini
中。 您必须在Tk()
之前(如果您想使用 confing 创建windgets)或在mainloop()
之前(如果您想更改现有小部件)阅读配置,并在mainloop()
之后(或更改状态时)保存它
我使用JSON
来保留配置,因为它是标准模块(因此您不必安装它),它将带有数字的文本转换为整数/浮点值,将文本“false/true”转换为 boolean 值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)
因为从文件中获取配置后,我还想更新 label 和按钮上的文本,所以我在创建所有小部件后读取配置。
# read after creating widgets because config updates text on label and buttons
load_config()
base.mainloop()
# save after closing window
save_config()
包含其他更改的完整代码
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.