Scenario:

  1. You want to use Pillow's ImageFile module,
  2. You are not using tcl, tkinter, or the TkImage class,
  3. PyInstaller is over-aggressively including all of tcl/tkinter in the dist.

Problem: There isn't clear documentation on the internet of how to actually remove these modules successfully. There's quite a bit of talk on SO with a lot of wrong/non-working advice on how to accomplish this.

Here's a simple spec file showing the changes I made to accomplish this.

Notice in particular two things:

  1. hacking sys.modules to remove FixTk

  2. The list of modules in Analysis (excludes=[])

    # -*- mode: python -*-
    
    block_cipher = None`
    
    import sys
    sys.modules['FixTk'] = None
    
    a = Analysis(['kill_tk_test.py'],
                 pathex=['C:\\code\\kill_tk_test'],
                 binaries=None,
                 datas=None,
                 hiddenimports=[],
                 hookspath=[],
                 runtime_hooks=[],
                 excludes=['FixTk', 'tcl', 'tk', '_tkinter', 'tkinter', 'Tkinter'],
                 win_no_prefer_redirects=False,
                 win_private_assemblies=False,
                 cipher=block_cipher)
    
    pyz = PYZ(a.pure, a.zipped_data,
              cipher=block_cipher)
    exe = EXE(pyz,
              a.scripts,
              exclude_binaries=True,
              name='kill_tk_test',
              debug=False,
              strip=False,
              upx=True,
              console=True )
    coll = COLLECT(exe,
                   a.binaries,
                   a.zipfiles,
                   a.datas,
                   strip=False,
                   upx=True,
                   name='kill_tk_test')