How to resolve error calling Python from MATLAB?
69 views (last 30 days)
Show older comments
I have both MATLAB 2022a and 2022b on the same machine. MATLAB 2022a always called python without any issue. But now I installed 2022b and Python doesn't work. How to fix this error? Thanks.
Error using __init__
Python Error: TclError: Can't find a usable init.tcl in the following
directories:
C:/Users/kkkAppData/Local/Programs/Python/Python39/lib/tcl8.6
{C:/Program Files/MATLAB/R2022b/bin/lib/tcl8.6} {C:/Program
Files/MATLAB/R2022b/lib/tcl8.6} {C:/Program
Files/MATLAB/R2022b/bin/library} {C:/Program
Files/MATLAB/R2022b/library} {C:/Program
Files/MATLAB/R2022b/tcl8.6.9/library} {C:/Program
Files/MATLAB/tcl8.6.9/library}
This probably means that Tcl wasn't installed properly.
0 Comments
Answers (1)
Shoaib iqbal
on 8 Nov 2022
Looking at the Python source code Modules\_tkinter.c, TCL uses hard coded location of tcl_library_path to find its initialization files which doesn't work when Python is loaded by MATLAB.
Here is an workaround:
>> setenv('TCL_LIBRARY', 'C:\Users\sji\AppData\Local\Programs\Python\Python38\tcl\tcl8.6')
>> setenv('TK_LIBRARY', 'C:\Users\sji\AppData\Local\Programs\Python\Python38\tcl\tk8.6')
>> py.tkinter.Tk
Run these commands every time you run MATLAB. Alternatively, place the commands in a MATLAB startup script.
3 Comments
Siyu
on 2 Feb 2023
For 2022b, there is another workaround, this error was resolved for some users by using the following code where "pyenv("ExecutionMode","OutOfProcess")" is used:
>> terminate(pyenv) % Adjusted: in case there is already a process running, we should stop it
>> pyStr = pyenv("ExecutionMode","OutOfProcess"); % Adjusted
>> pyTCL = fullfile(pyStr.Home, 'tcl', 'tcl8.6');
>> pyTK = fullfile(pyStr.Home, 'tcl', 'tk8.6');
>> setenv('TCL_LIBRARY', pyTCL);
>> setenv('TK_LIBRARY', pyTK);
The 'OutOfProcess' input in "pyenv" starts a separate process and is used for safe execution of Python scripts and libraries. Also, "terminate(pyenv)" was added to stop any "pyenv" processes which may be running. More can be read about this here: https://www.mathworks.com/help/matlab/ref/pyenv.html?searchHighlight=pyenv&s_tid=srchtitle_pyenv_1#mw_33379b1a-e442-4992-8a9a-d2e7646953a4.
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!