Python Forum

Full Version: [TKINTER] Problems creating directories in a selected path
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello.

I believe that my problem is easy to be solved, but I've already researched it in forums and other websites but I couldn't solve it.

I'm trying to create a small application, which opens a window with TKINTER and when I click on the button and select a directory. This application must create other directories in the path that was indicated when selecting the button.

My code
import os
from tkinter import *
import tkinter.filedialog

janela = Tk()
janela.title('TESTE')
janela.geometry('200x200')

def createDirectory():
    os.chdir(sourcePath)
    directory = 'Data'
    os.makedirs(directory)

def selectDirectory():
    sourcePath = filedialog.askdirectory()
    createDirectory()
    
selectButton = Button(janela, text='Select Diretory', width=15, command=selectDirectory)
selectButton.grid(column=0, row=0, padx=10, pady=10)

janela.mainloop()
This is the error message, that i'm receiving.

Error:
Exception in Tkinter callback Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "<ipython-input-2-737f6accf91d>", line 16, in selectDirectory createDirectory() File "<ipython-input-2-737f6accf91d>", line 10, in createDirectory os.chdir(sourcePath) NameError: name 'sourcePath' is not defined
You need to pass the sourcePath

import os
from tkinter import *
import tkinter.filedialog
 
janela = Tk()
janela.title('TESTE')
janela.geometry('200x200')
 
def createDirectory(sourcePath):
    os.chdir(sourcePath)
    directory = 'Data'
    os.makedirs(directory)
 
def selectDirectory():
    sourcePath = filedialog.askdirectory()
    createDirectory(sourcePath)
     
selectButton = Button(janela, text='Select Diretory', width=15, command=selectDirectory)
selectButton.grid(column=0, row=0, padx=10, pady=10)
 
janela.mainloop()
Thank you for answering my question. Big Grin

(Aug-10-2021, 07:57 AM)Larz60+ Wrote: [ -> ]You need to pass the sourcePath

import os
from tkinter import *
import tkinter.filedialog
 
janela = Tk()
janela.title('TESTE')
janela.geometry('200x200')
 
def createDirectory(sourcePath):
    os.chdir(sourcePath)
    directory = 'Data'
    os.makedirs(directory)
 
def selectDirectory():
    sourcePath = filedialog.askdirectory()
    createDirectory(sourcePath)
     
selectButton = Button(janela, text='Select Diretory', width=15, command=selectDirectory)
selectButton.grid(column=0, row=0, padx=10, pady=10)
 
janela.mainloop()