代码之家  ›  专栏  ›  技术社区  ›  user12860710

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

  •  0
  • user12860710  · 技术社区  · 2 年前
    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个条目运行测试。

    提前谢谢。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Emmanuel    2 年前

    Tkinter中的文件对话框需要 活动Tkinter应用程序上下文 . 在启动函数调用之前,需要以下代码

    root = tk.Tk()
    root.withdraw()
    

    root.withdraw() 被添加以隐藏您初始化的根窗口。

    因此,整个文件将看起来像:

    import os
    import tkinter as tk
    from tkinter import filedialog
    
    root = tk.Tk()
    root.withdraw()
    
    def add_numbers():
       ...
    
    add_numbers()