Search code examples
pythontkinteruser-inputfilepath

tkinter - How to use file path entered into Entry widget as a variable?


I have this GUI that generates an Entry widget and a Button widget. The user is supposed to enter a file path (example "C:\Users\example\example") and that file path is used as the variable for the function LoopAnalysis().

When I execute the code, the widgets work and I can copy and paste a file path into the Entry widget, but when I execute the command using the Button widget I get the following error:

FileNotFoundError: [WinError 3] The system cannot find the path specified: ''

If the user inputs in the Entry window a file path, is there a specific syntax to use it as a variable? For example I know that for python in general if I manually define a variable as such.

Directory = r'C:\Users\example\example'

I need to add the r before the file path for python to recognize the entire line as a file path and not consider the special characters in the file path.

How do I do this for my function?

Torque_Analysis is already defined and works properly.

ws = Tk()
ws.title("Torque Analysis")
ws.geometry('1000x150')
ws['bg'] = 'black'

def LoopAnalysis(Directory):
    for filename in os.listdir(Directory):
        if filename.endswith(".csv"):
            Torque_Analysis(os.path.join(Directory, filename))
            plt.figure()
            plt.show(block = False)
        else: continue

UserEntry = Entry(ws, width = 150)
UserEntry.pack(pady=30)
Directory = UserEntry.get()

Button(ws,text="Click Here to Generate Curves", padx=10, pady=5, command=lambda: LoopAnalysis(Directory)).pack()

ws.mainloop()

Solution

  • As stated in a comment to the question, you are calling UserEntry.get() once, as soon as the program starts. The entry box is blank then, so that blank string is read and stored in Directory, and the contents of Directory never changes again.

    Instead, you need to call UserEntry.get() every time the button is pressed.

    Try this:

    from tkinter import *
    import os
    
    ws = Tk()
    ws.title("Torque Analysis")
    ws.geometry('1000x150')
    ws['bg'] = 'black'
    
    def LoopAnalysis(Directory):
        for filename in os.listdir(Directory):
            if filename.endswith(".csv"):
                Torque_Analysis(os.path.join(Directory, filename))
                plt.figure()
                plt.show(block = False)
            else: continue
    
    UserEntry = Entry(ws, width = 150)
    UserEntry.pack(pady=30)
    Button(ws,text="Click Here to Generate Curves", padx=10, pady=5, command=lambda: LoopAnalysis(UserEntry.get())).pack()
    
    ws.mainloop()