PyInstaller + Tkinter within Virtual Environment -- failed to built an executable in python 3.8

77 Views Asked by At

Question

I have tried to built an executable with PyInstaller. A very similar question was asked here.

I am doing this from a WSL terminal on a Windows machine. I have created a virtual environment to reduce the amount of packages which are imported in my executable. Currently my script uses pandas, requests and tkinter.

I installed all the necessary packages via pip in my environment. And ran the PyInstaller with the following command (already trying the solution from the question above):

sudo pyinstaller --onefile --hidden-import=tkinter search_ucdp.py

In case i get asked this I installed the tkinter as follows:

sudo pip install tk

My problem is that I cannot get the executable running, no matter what i tried. It gives me the following error indicating that the tkinter module/library was not found:

Traceback (most recent call last):
File "[myscript].py", line 2, in <module>
ModuleNotFoundError: No module named 'tkinter'
[26040] Failed to execute script '[my_script]' due to unhandled exception!

Another thing i found strange was that the executable is generated without the .exe (but my guess is due to it being generated in a linux environment(?)).

The file is recognized as an executable and if i generate it outside the virtual environment it works. But why does it not work here?

What I tried:

  • I played around with the --hidden-import from pyinstaller trying "tk" and "tkinter", but that results in the same error

  • I also tried modifying the pip statements (same as above)

  • relating to this question -> PyInstaller is installed both within the venv as well as globally

1

There are 1 best solutions below

1
Sauron On
  • Not able to reproduce the error, but you mentioned using --additional-hooks-dir: Sometimes PyInstaller might not be able to detect all necessary imports automatically. You can try providing additional hooks to help PyInstaller find the tkinter module. Create a directory (e.g., hooks) and create a file named hook-tkinter.py inside it with the following content:
from PyInstaller.utils.hooks import collect_submodules

hiddenimports = collect_submodules('tkinter')

Then, specify this directory using the --additional-hooks-dir option when running PyInstaller

  • And Also refer to the comment by @phd