如何让代码要求我选择要保存文件的文件夹?

问题描述 投票:0回答:1
import os
import tkinter as tk
from tkinter import filedialog

def add_numbers():
    attempts = 0
    results = []

    while attempts < 3:
        try:
            num1 = float(input("Enter the first number: "))
            num2 = float(input("Enter the second number: "))

            result = num1 + num2
            equation = f"{num1} + {num2} = {result}"

            print(equation)
            results.append(equation)
            attempts += 1

        except ValueError:
            attempts += 1
            print("Invalid input. Please enter valid numbers.")

    save_filename = "results.txt"
    folder = filedialog.askdirectory()
    save_location = os.path.join(folder, save_filename)
    
    with open(save_location, 'w') as file:
        for equation in results:
            file.write(equation + '\n')
    

    print(f"Results have been saved to {save_location}")
    print("You have reached the maximum number of attempts. Exiting.")


if __name__ == "__main__":
    add_numbers()

嗨,我希望它能够让我选择计算机中的位置来保存名为 result.txt 的结果文件。 这是我迄今为止用 Python 编写的内容。

以下是要求:

编写一个程序,不断要求用户输入两个数字相加(完成后退出)。 对于程序执行的每次加法,将结果存储在文件“data//results.txt”中。应将整个方程相加,而不仅仅是总和。 例如,如果用户输入“2”和“4”,则应将以下文本附加到文件中: 2 + 4 = 6 该程序应该是循环的,因此请尝试对将存储在 result.txt 中的 3 个条目运行测试。

提前谢谢您。

python loops math directory numbers
1个回答
0
投票

Tkinter 中的文件对话框需要一个活动的 Tkinter 应用程序上下文。 在发起函数调用之前,您需要以下代码

root = tk.Tk()

因此,整个文件将如下所示:

import os
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()

def add_numbers():
   ...

add_numbers()
© www.soinside.com 2019 - 2024. All rights reserved.