Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 40 ยท Packaging and Patterns

Packaging a Tkinter App: PyInstaller, Resources and Settings

Turn a Tkinter program into an .exe or app with PyInstaller: one-file builds, bundled images and icons, resource paths, user settings files and common build errors.

A Tkinter program that runs on your laptop is not yet a product. Your users do not have Python, do not want a terminal, and certainly do not want to type pip install. Packaging turns your script into something they can double-click: an .exe on Windows, a .app on macOS, or a single binary on Linux.

The most widely used tool is PyInstaller. This lesson shows a complete build, the two issues that break nearly every first attempt (bundled files and writable settings), and alternatives. Command lines and project files are read-only on this page (they run in a terminal, not in the browser); the runnable blocks implement the path and settings logic you must add to your own code, with plain Python.

What PyInstaller does

PyInstaller analyzes your imports, collects your code, the Python interpreter, the libraries and Tcl/Tk, and bundles them into a folder or a single file. It does not compile your code to machine code and it does not cross-compile: to get a Windows .exe you build on Windows, for macOS you build on a Mac, for Linux on Linux.

TEXT
pip install pyinstaller
pyinstaller --noconsole --onefile --name Notes --icon app.ico main.py

The first run takes a minute. Afterwards you find:

TEXT
build/        temporary files
dist/Notes.exe   the result (one file)
Notes.spec    the build recipe
Option Meaning
--onefile / -F one self-extracting file (slower start)
--onedir (default) a folder with the exe and its libraries (faster start, easier to debug)
--noconsole / -w no black console window (needed for GUI programs)
--name name of the output
--icon app.ico exe icon (.icns on macOS)
--add-data "src;dest" bundle extra files (; on Windows, : on macOS and Linux)
--hidden-import mod include a module PyInstaller could not detect
--clean clear caches before building

Start with --onedir and --console while you debug, because errors print in the console. Switch to --noconsole --onefile when the program works.

From script to installer

Script main.py plus your modules
PyInstaller Collects Python, Tk and libraries
Executable dist/Notes.exe
Installer Optional: Inno Setup, DMG, .deb

Build on each target operating system.

1 / 2

Problem 1: bundled files are not where you expect

Your program loads logo.png with tk.PhotoImage(file="logo.png"). In development this works because the current folder is your project. In a one-file build PyInstaller unpacks everything to a temporary folder (exposed as sys._MEIPASS) every time the program starts, and the current folder is wherever the user launched it. The image is not found and the program crashes at start.

The fix has two parts. First, tell PyInstaller to include the file:

TEXT
pyinstaller --noconsole --onefile --add-data "assets;assets" main.py

Second, resolve the path in code with a helper that works both ways:

Python
import sys
from pathlib import Path

def resource_path(relative):
    base = getattr(sys, "_MEIPASS", None)         # set only in a PyInstaller build
    root = Path(base) if base else Path(__file__).resolve().parent
    return str(root / relative)

logo = tk.PhotoImage(file=resource_path("assets/logo.png"))

getattr(sys, "_MEIPASS", None) is a defined attribute inside a frozen program and absent when you run the script normally. This function is the single most useful piece of packaging code. The stand-in below runs it in both situations by faking the attribute.

Python Run: resource_path in development and in a frozen build

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Problem 2: you cannot write next to the program

A program installed in C:\Program Files (or inside the temporary folder of a one-file build) is not allowed to save files beside itself, and anything written to the temp folder disappears on exit. User data (settings, saved documents, logs) belongs in the user's own application-data folder:

System Typical settings folder
Windows %APPDATA%\YourApp
macOS ~/Library/Application Support/YourApp
Linux ~/.config/yourapp
Python
import json, os, sys
from pathlib import Path

def settings_path(app="notes"):
    if sys.platform == "win32":
        base = Path(os.environ.get("APPDATA", Path.home()))
    elif sys.platform == "darwin":
        base = Path.home() / "Library" / "Application Support"
    else:
        base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
    folder = base / app
    folder.mkdir(parents=True, exist_ok=True)
    return folder / "settings.json"

Load settings at start (with defaults when the file is missing or damaged) and save them when the window closes (root.protocol("WM_DELETE_WINDOW", on_close), see Toplevel Windows and Custom Dialogs). A good settings loader never crashes the program:

Python Run: a settings loader that survives missing and broken files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Writing to a temporary file and replacing the old one (os.replace) keeps the settings intact even if the program is killed in the middle of saving.

The spec file

PyInstaller writes Notes.spec, a Python script describing the build. Editing it is the clean way to keep options in version control:

Python
# Notes.spec (excerpt)
a = Analysis(
    ["main.py"],
    datas=[("assets", "assets")],          # (source, destination folder in the bundle)
    hiddenimports=["tkinter.tix"],
)
exe = EXE(
    pyz, a.scripts, a.binaries, a.datas, [],
    name="Notes",
    console=False,
    icon="app.ico",
    upx=False,
)

Build from the spec with pyinstaller Notes.spec. Changing command-line options after a spec exists has no effect; edit the spec instead. Keep upx=False unless you have a reason: compressed executables trigger more antivirus warnings.

Common build problems

  • "Failed to execute script" / window flashes and closes. Rebuild without --noconsole to read the traceback. Usually a missing data file or hidden import.
  • File not found at start. You loaded a resource with a relative path; use resource_path and --add-data.
  • Missing module. Imports done with importlib.import_module("name") or plugins are invisible to the analyzer. Add --hidden-import name.
  • Huge output. Building inside a global environment packs everything installed. Use a virtual environment containing only your dependencies.
  • Antivirus false alarms. One-file builds that self-extract sometimes get flagged. Prefer --onedir plus an installer, avoid UPX, and sign the executable with a code-signing certificate if you distribute widely.
  • Slow start. One-file builds unpack at every launch; --onedir starts faster.
  • Wrong icon or blurry window on high-DPI displays. On Windows call ctypes.windll.shcore.SetProcessDpiAwareness(1) before creating the window, and supply a multi-size .ico.
  • macOS Gatekeeper warnings. Downloaded apps need code signing and notarization to open without a warning.

Alternatives

Tool Notes
cx_Freeze Similar idea; builds folders and MSI installers
Nuitka Compiles Python to C; faster programs, longer builds
py2app macOS-only .app bundles
Briefcase (BeeWare) Packaging for desktop and mobile with installers
zipapp / pip install Ship as a Python package or .pyz if users already have Python
Inno Setup, NSIS, WiX Wrap a PyInstaller folder into a Windows installer

A normal release flow is: build a --onedir bundle in CI for each operating system, test it on a clean machine without Python, then wrap it in an installer.

Pre-release checklist

Python Run: checklist helper for a release folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Using relative paths for images and data files.
  • Saving user data next to the program instead of the user's app-data folder.
  • Building on a machine with every library installed.
  • Shipping a build you never ran on a clean computer.
  • Forgetting --noconsole (a black window appears) or using it before the program works (errors are invisible).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does open('logo.png') fail in a one-file PyInstaller build?

    Resolve paths relative to sys._MEIPASS in a frozen app (and the script folder in development).
  2. 2. Which option removes the black console window of a GUI app?

    --noconsole builds a windowed program; use a console build while debugging.
  3. 3. Where should user settings be stored?

    Program folders may be read-only and the temp folder is deleted when the program exits.
  4. 4. Can you build a Windows .exe with PyInstaller on Linux?

    Build on each target platform (a CI matrix is the usual approach).

Summary

  • PyInstaller bundles your script, Python and Tk; build on each target OS.
  • Start with --onedir and a console; finish with --noconsole.
  • Bundle data with --add-data and find it with a resource_path helper that checks sys._MEIPASS.
  • Save settings in the user's app-data folder; load them defensively and save atomically.
  • Test on a clean machine; consider an installer and code signing.

Next: Project: A Calculator