An Dowe
An Dowe

Reputation: 13

Set working directory through tkinter in python

I have the following code which basically helps me get first the path of a folder and then set the working directory to that specific folder.

I do get the following error message though:

os.chdir(sourcePath)  # Provide the path here
FileNotFoundError: [Errno 2] No such file or directory: 'PY_VAR0'

The code:

from tkinter import filedialog
from tkinter import *
import glob, os, shutil

def browse_button():
    # Allow user to select a directory and store it in global var
    # called folder_path
    global folder_path
    filename = filedialog.askdirectory()
    folder_path.set(filename)
    print(filename)

def set_dir():
    sourcePath = str(folder_path)
    os.chdir(sourcePath)  # Provide the path here


root = Tk()

folder_path = StringVar()

lbl1 = Label(master=root,textvariable=folder_path)
lbl1.grid(row=0, column=1)

buttonBrowse = Button(text="Browse folder", command=browse_button)
buttonBrowse.grid(row=2, column=1)
buttonSetDir = Button(root, text='Set directory', command=set_dir).grid(row=2, column=2, sticky=W, pady=4)
mainloop()

Upvotes: 1

Views: 3465

Answers (1)

Nae
Nae

Reputation: 15335

Replace:

sourcePath = str(folder_path)

with:

sourcePath = folder_path.get()

str(folder_path) basically gets the variable's interpreter name.

Upvotes: 1

Related Questions