Search code examples
pythontkinterdirectory

How do I make the code ask me to choose the folder I want to save a file in?


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

Hi, I would like it to let me choose the location in my computer to save the result file named result.txt. This is what I've written so far, in Python.

Here are the requirements:

Write a program that continually asks the user for two numbers to add (and quits when they are finished). For each addition the program performs, store the results in a file “data//results.txt”. The entire equation should be added, not just the sum. For example, if the user enters “2” and “4”, the following text should be appended to the file: 2 + 4 = 6 The program should be looping so try running a test for 3 entries that would be stored in result.txt.

Thank you in advance.


Solution

  • File dialogs in Tkinter require an active Tkinter application context. you need the following code before you initiate the function call

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

    root.withdraw() was added to hide the root window you initialised.

    so, the overall file will look like:

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