【问题标题】:Python tkinter save new results in text filePython tkinter 将新结果保存在文本文件中
【发布时间】:2018-04-24 13:30:27
【问题描述】:

我想问一个关于在 python 中使用tkinter 或我可以使用的任何其他方法加载某个 txt 文件的问题。这是我制作的“测试”程序。enter image description here

每个按钮都会计算输入数字的一定百分比。 在我输入一个数字并计算该数字的百分比后,假设我输入 100,其中 80% 是 80。结果显示出来,之后我想使用 "Add new max" 按钮将该结果保存在一个文本文件中. 当我打开程序保存结果后,它应该显示"Current max: 80"。所以基本上把计算出来的结果保存下来,每次打开程序都显示出来。

假设"current saved result"80,我计算出一个大于current result(80) 的新值并因此被替换。

在我附上的图片中:

      test1 = x

如果我输入的新值大于 x,x 应该被新值替换。 (忽略 test2, test3)

我应该使用什么来做到这一点?

提前谢谢你们!

【问题讨论】:

  • 您不确定哪一部分该怎么做?写文件?阅读它?按下按钮时触发保存事件?
  • 您的问题不清楚,具体您需要什么帮助?

标签: python tkinter load overwrite


【解决方案1】:

这并不难。

写入文件:

f = open( 'name_of_a_file', 'w' ) #(w = write)
f.write(some_data_or_something)
f.close()

读取文件:

try:
    fh = open('name_of_a_file', "r")
    some_data = fh.read()
    fh.close()

except IOError:
    print("could not load the file.")

**完整代码 - 保存文件,然后将其拉回并打印:

some_data_or_something = 'hello'
f = open( 'name_of_a_file', 'w' ) #(w = write)
f.write(some_data_or_something)
f.close()

try:
    fh = open('name_of_a_file', "r") #(r = read)
    some_data = fh.read()
    fh.close()
    print(some_data)

except IOError:
    print("could not load the file.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多