Skip to content

Implement Tkinter GUI with Windows .exe Compilation #34

@AliiiBenn

Description

@AliiiBenn

Implement Tkinter GUI with Windows .exe Compilation

Problem Description

Wareflow Analysis currently requires users to be comfortable with command-line interfaces (CLI) to perform warehouse data analysis operations. Non-technical users (warehouse managers, business analysts, operations staff) face barriers to adoption due to:

  1. CLI learning curve - Need to memorize commands and options
  2. Error-prone - Typos in commands lead to frustration
  3. No visual feedback - Hard to understand progress and status
  4. File management - Manual directory navigation and file placement
  5. Perception - Seen as "developer tool" rather than business tool

A Graphical User Interface (GUI) would make the tool accessible to non-technical users while maintaining all existing CLI functionality for power users.

Target Audience

Primary Users:

  • Warehouse managers (non-technical)
  • Business analysts
  • Operations staff
  • Small business owners

Secondary Users:

  • Technical users who prefer GUI over CLI
  • Data analysts who want visual workflow

Proposed Solution

Implement a cross-platform Tkinter GUI that:

  1. Wraps existing CLI functionality - No code duplication
  2. Compiles to Windows .exe - Easy distribution, no Python required
  3. Maintains CLI compatibility - Both interfaces work simultaneously
  4. Provides visual feedback - Progress bars, status indicators, error dialogs
  5. Simplifies complex workflows - Wizards for multi-step operations

High-Level Architecture

┌─────────────────────────────────────────────────┐
│         GUI LAYER (NEW)                         │
│  ┌─────────────────────────────────────────┐   │
│  │  src/wareflow_analysis/gui/            │   │
│  │  ├── __init__.py                       │   │
│  │  ├── main_window.py                    │   │
│  │  ├── views/                            │   │
│  │  │   ├── home_view.py                  │   │
│  │  │   ├── import_view.py                │   │
│  │  │   ├── analyze_view.py               │   │
│  │  │   ├── export_view.py                │   │
│  │  │   └── status_view.py                │   │
│  │  ├── controllers/                      │   │
│  │  │   └── app_controller.py             │   │
│  │  └── widgets/                          │   │
│  │      ├── progress_bar.py               │   │
│  │      ├── file_selector.py              │   │
│  │      └── status_display.py             │   │
│  └─────────────────────────────────────────┘   │
└─────────────────────────────────────────────────┘
                      ↓
┌─────────────────────────────────────────────────┐
│         BUSINESS LOGIC (EXISTING)               │
│  - CLI commands remain unchanged                │
│  - Logic extracted into reusable functions     │
│  - Flexible output handling (CLI/GUI)           │
└─────────────────────────────────────────────────┘

UI/UX Design

Main Window Layout

┌─────────────────────────────────────────────────┐
│  Wareflow Analysis                    [_][□][X] │
├─────────────────────────────────────────────────┤
│  🏠 Home  📥 Import  📊 Analyze  📤 Export     │
├─────────────────────────────────────────────────┤
│                                                 │
│  [Dynamic content based on selected view]      │
│                                                 │
│                                                 │
├─────────────────────────────────────────────────┤
│  Status: Ready | Project: /path/to/project      │
└─────────────────────────────────────────────────┘

Key Views

1. Home View (Dashboard)

  • Project status overview
  • Database statistics (tables, row counts)
  • Recent activity log
  • Quick action buttons
  • Last opened project (auto-recall)

2. Import View

  • Step-by-step wizard
  • File browser for Excel files
  • Configuration generator (Auto-Pilot)
  • Real-time progress bar
  • Import summary with success/error counts
  • Backup toggle

3. Analyze View

  • Analysis type selector (ABC, Inventory)
  • Parameter configuration (lookback days, etc.)
  • Run button with progress indication
  • Results preview (table/grid)
  • Option to export immediately

4. Export View

  • Analysis source selector
  • Output filename input
  • Directory browser
  • Format options (if applicable)
  • Export progress and completion dialog

5. Status View

  • Database schema display
  • Table row counts
  • Database file size
  • Last import timestamp
  • Configuration file summary

Technical Implementation

Phase 1: Foundation (1-2 days)

Tasks:

  1. Create src/wareflow_analysis/gui/ directory structure
  2. Implement main_window.py with basic navigation
  3. Create StateManager class for project state tracking
  4. Implement flexible OutputHandler (CLI/GUI switchable)
  5. Set up basic styling (consider ttkbootstrap for modern look)

Deliverables:

  • Working main window with navigation
  • State management system
  • No freezing during operations (threading ready)

Phase 2: Home & Import Views (1-2 days)

Tasks:

  1. Implement HomeView with project status
  2. Create ImportView with file browser
  3. Integrate with existing importer.py module
  4. Add progress bar with threading
  5. Implement success/error dialogs
  6. Add Auto-Pilot configuration generation

Deliverables:

  • Full import workflow functional
  • Visual progress feedback
  • Error handling with user-friendly messages

Phase 3: Analyze & Export Views (1 day)

Tasks:

  1. Implement AnalyzeView with dropdown selection
  2. Create ExportView with file dialogs
  3. Integrate with analyze/*.py modules
  4. Integrate with export/reports/*.py modules
  5. Add results preview table
  6. Implement post-analysis export flow

Deliverables:

  • Complete analysis workflow
  • Export functionality
  • Results visualization

Phase 4: Status & Validation Views (1 day)

Tasks:

  1. Implement StatusView with database info
  2. Create validation results display
  3. Add interactive error fixing (checkbox per error)
  4. Implement confirmation dialogs for destructive operations
  5. Add "Dry Run" mode visualization

Deliverables:

  • Complete status dashboard
  • Interactive validation
  • Safe operation confirmations

Phase 5: Compilation & Packaging (0.5-1 day)

Tasks:

  1. Set up PyInstaller configuration
  2. Create application icon
  3. Test on clean Windows machine
  4. Create installer (NSIS or InnoSetup)
  5. Write user documentation

Deliverables:

  • Working Wareflow-GUI.exe
  • Installation package
  • User guide

Code Modifications Required

1. Flexible Output Handling

Create src/wareflow_analysis/common/output_handler.py:

from typing import Callable, Optional

class OutputHandler:
    """Handle output for both CLI and GUI."""

    def __init__(self, mode: str = "cli", callback: Optional[Callable] = None):
        self.mode = mode  # "cli" or "gui"
        self.callback = callback

    def print(self, message: str):
        """Print message based on mode."""
        if self.mode == "cli":
            print(message)
        elif self.mode == "gui" and self.callback:
            self.callback(message)

    def error(self, message: str):
        """Print error message based on mode."""
        if self.mode == "cli":
            print(f"Error: {message}", file=sys.stderr)
        elif self.mode == "gui" and self.callback:
            self.callback(f"ERROR: {message}")

2. Extract CLI Callbacks

Refactor cli.py to remove Typer dependencies from business logic:

# Current: CLI directly calls functions
def import_data(init_config: bool = False, verbose: bool = True):
    success, message = run_import(project_dir, verbose)
    typer.echo(message)

# Proposed: Reusable function
def import_data(project_dir: Path, init_config: bool = False,
                verbose: bool = True, output_handler: OutputHandler = None):
    if output_handler is None:
        output_handler = OutputHandler(mode="cli")

    success, message = run_import(project_dir, verbose, output_handler)
    output_handler.print(message)
    return success, message

3. Threaded Operations

import threading
from queue import Queue

class ThreadedOperation:
    """Run operations in background thread."""

    def __init__(self, operation, callback=None):
        self.operation = operation
        self.callback = callback
        self.queue = Queue()

    def start(self):
        """Start operation in background thread."""
        thread = threading.Thread(target=self._run)
        thread.daemon = True
        thread.start()

    def _run(self):
        """Run operation and put result in queue."""
        result = self.operation()
        self.queue.put(result)
        if self.callback:
            self.callback(result)

Dependencies

Add to pyproject.toml:

[project.dependencies]
# ... existing dependencies ...

[project.optional-dependencies]
gui = [
    "ttkbootstrap>=1.10",  # Modern theming for tkinter
    "pillow>=10.0",       # Image handling for icons
]

[project.scripts]
wareflow = "wareflow_analysis.cli:cli"
wareflow-gui = "wareflow_analysis.gui:main"  # New entry point

Compilation Strategy

Recommended: PyInstaller

Advantages:

  • Most mature and stable
  • Excellent tkinter support
  • Cross-platform (Windows/Mac/Linux)
  • Can create single-file executable

Configuration:

# build.spec
a = Analysis(
    ['src/wareflow_analysis/gui/__main__.py'],
    pathex=[],
    binaries=[],
    datas=[
        ('src/wareflow_analysis', 'wareflow_analysis'),
        ('assets', 'assets'),  # Icons, images
    ],
    hiddenimports=[
        'tkinter',
        'pandas',
        'openpyxl',
        'yaml',
        'sqlite3',
    ],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=None,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=None)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='Wareflow Analysis',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,  # Windowed mode
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon='assets/icon.ico',
)

Build Command:

pyinstaller build.spec --clean --noconfirm

Alternative: cx_Freeze (Lighter)

# setup.py
from cx_Freeze import setup, Executable

build_exe_options = {
    "packages": ["tkinter", "pandas", "openpyxl"],
    "include_files": ["src/wareflow_analysis", "assets"],
    "excludes": [],
}

executables = [
    Executable(
        script="src/wareflow_analysis/gui/__main__.py",
        base="Win32GUI" if sys.platform == "win32" else None,
        target_name="Wareflow-GUI.exe",
        icon="assets/icon.ico",
    )
]

setup(
    name="Wareflow Analysis",
    version="0.6.0",
    description="Warehouse data analysis GUI",
    options={"build_exe": build_exe_options},
    executables=executables,
)

Success Criteria

Functionality

  • All CLI operations accessible via GUI
  • Import workflow complete with progress feedback
  • Analysis and export workflows functional
  • Project status dashboard displays correctly
  • Validation results shown interactively
  • Error messages user-friendly and actionable

User Experience

  • No GUI freezing during operations (threading)
  • Intuitive navigation between views
  • Clear visual feedback for all actions
  • Confirmation dialogs for destructive operations
  • File browsers for all file selections
  • Progress bars for long-running operations

Technical

  • Zero breaking changes to existing CLI
  • Code reuse > 90% (minimal duplication)
  • GUI code properly separated from business logic
  • Compiled .exe runs on clean Windows machine
  • Memory usage reasonable (< 200MB idle)
  • Startup time < 3 seconds

Documentation

  • User guide for GUI features
  • Installation instructions for .exe
  • Troubleshooting guide
  • Screenshots in documentation

Migration Path

For Existing CLI Users

  • No changes required - CLI continues to work
  • Can optionally install GUI dependencies
  • Can use both interfaces interchangeably

For New GUI Users

  • Download .exe from releases
  • No Python installation required
  • Double-click to run
  • Same project structure as CLI version

Risks & Mitigation

Risk Impact Mitigation
Tkinter looks dated Medium Use ttkbootstrap for modern styling
Threading complexity High Start simple, add threading after basic GUI works
Large .exe size Low Acceptable trade-off for ease of distribution
Windows-only .exe Low Provide pip install instructions for Mac/Linux
Maintaining two interfaces Medium Shared business logic minimizes duplication
Testing GUI code Medium Manual testing checklist + unit tests for logic

Future Enhancements (Post-MVP)

  1. Dark mode - Theme switching
  2. Custom themes - Branding options
  3. Workflow automation - Scheduled imports/exports
  4. Charts and graphs - Visual analysis results
  5. Multi-language - i18n support (French, English)
  6. Configuration UI - Visual config.yaml editor
  7. Database browser - View and edit data directly
  8. Report templates - Customizable report formats

References

Estimation

Total Effort: 4-6 days

Breakdown:

  • Phase 1 (Foundation): 1-2 days
  • Phase 2 (Home/Import): 1-2 days
  • Phase 3 (Analyze/Export): 1 day
  • Phase 4 (Status/Validation): 1 day
  • Phase 5 (Compilation): 0.5-1 day

Dependencies:

  • Requires approval of architecture approach
  • Requires Windows machine for final testing
  • Requires icon/design assets (or use placeholders)

Priority: Medium-High

  • Strategic value: High (expands user base)
  • Technical risk: Low (leverages existing code)
  • Effort: Moderate

Issue ID: 002
Created: 2025-01-26
Last Updated: 2025-01-26
Status: Open
Assignee: TBD
Labels: enhancement, gui, user-experience, windows
Milestone: v1.0.0 or v0.7.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions