I try to create a simple GUI app with tkinter and customtkinter using python. The program works fine when I try to run it from an IDE or when I try to run the .py file. It simply works with no problem.
So I tried to generate an .exe file with pyinstaller with this:
PyInstaller checklist_app2.py --add-data "images;images" --add-data "assets;assets" --add-data "C:/Users/U-ser/AppData/Local/Programs/Python/Python312/Lib/site-packages/customtkinter;customtkinter/" --window --noupx
Then, if I tried to run the .exe file from the command prompt. Basically just put the path to the exe file like this:
dist\checklist_app2\checklist_app2.exe
and it still works JUST FINE with no problem at all. Everything works the same way as if I were to run from IDE.
HOWEVER, when I try to double-click the .exe file itself. It gives me this error window:
Traceback (most recent call last):
File "checklist_app2.py", line 588, in <module>
File "checklist_app2.py", line 27, in __init__
File "checklist_app2.py", line 400, in get_items_dict
IndexError: list index out of range
I'm sure it's not an indexing problem because it worked fine in the IDE, and it worked fine when running the .exe from the command line, but somehow, when I double-click, it gives me this IndexError: list index out of range.
How do I handle this issue where it behave differently when double click and when running exe from the commandline.
I have tried so so many thing. I have tried to specify pyinstaller to run a python3 version and many more. I spend half a day searching this issue and found no one talking about it.
It is also important to note that:in that line 400, inside the get_item_dict function. I have this code:
images_paths = list(walk(folder_path))[0][2]
And presumably, that is where the error occurs. The 'folder_path' is a string that is a path to a folder. That folder is the 'images' folder which I already include with --add-data when using pyinstaller. the walk function, turn it into some object that you can use list() to turn it into a python list. Then, I index it with the [0][2] to get a list of the content of that folder. But I feel like this is not an issue since it runs just fine when running .exe from the command line.
Since you have used relative path, it causes the exception because when you double-click the executable to run it, the current working directory will not be the project folder where the relative path is.
So list(walk(folder_path))
will return empty list which exception raised when you try to access element inside it.
Since you have already included the images
folder into the executable, and that folder will be extracted into a temporary folder along with the program files when the executable is being executed. The final temporary folder can be determined by the following code:
from pathlib import Path
...
# get the folder where the program file is
prog_dir = Path(__file__).parent
# create the absolute path for the "images" folder
folder_path = prog_dir / "images"
...