A comprehensive Python-based election management application designed for school and classroom elections. This system provides a secure, user-friendly interface for managing elections, candidates, and voting processes on a single machine.
- Features
- System Requirements
- Installation
- Quick Start
- Architecture
- Usage Guide
- Database Schema
- Security Features
- Export Formats
- Configuration
- Screenshots
- Troubleshooting
- Contributing
- Multi-Election Support: Create and manage multiple elections with independent candidate pools
- Candidate Management: Add, edit, and delete candidates with optional symbol images
- Secure Voting Interface: Full-screen kiosk mode preventing access to other applications
- Real-time Results: View live vote counts and percentage calculations
- NOTA Support: Automatic "None of the Above" option for democratic compliance
- Password Protection: SHA-256 hashed admin authentication for election management
- Multiple Export Formats: JSON, CSV, and PDF reports with comprehensive data
- Automatic Timestamping: All exports include generation timestamps for audit trails
- Symbol Integration: Candidate symbols embedded in PDF reports
- Fallback Support: Text reports generated when PDF dependencies unavailable
- Intuitive GUI: Clean, modern interface with optimized spacing and typography
- Audio Feedback: System beep sounds for vote confirmation and administrative actions
- Responsive Design: Adaptive layout supporting various screen resolutions
- Accessibility: High contrast colors and large fonts optimized for voting scenarios
- Primary: Ubuntu 22.04 LTS (fully optimized and tested)
- Compatible: Any Linux distribution with X11 display server
- Limited Support: Windows, macOS (some audio and system integration features unavailable)
- Python: 3.8 or higher (3.10+ recommended)
- Core Libraries: Tkinter (GUI), SQLite3 (database), Pillow (image processing)
- Optional Libraries: ReportLab (PDF generation), PulseAudio utilities (enhanced audio)
- Minimum RAM: 2GB available memory
- Storage: 100MB free disk space for application and database
- Display: 1024x768 minimum resolution (1920x1080 recommended)
- Audio: Optional sound card for voting feedback audio
The automated setup script handles all dependencies, environment configuration, and installation steps.
# Download and run the setup script
wget https://raw.githubusercontent.com/Pixelrick420/Election/main/setup.sh
chmod +x setup.sh
./setup.shThe setup script performs the following operations:
- System compatibility verification (Ubuntu 22.04 optimization)
- Package repository updates
- Git, Python3, and development tools installation
- Repository cloning from GitHub
- Virtual environment creation and activation
- Python dependency installation and compilation
- Directory structure creation
- Optional desktop shortcut generation
- Application launch verification
git clone https://github.com/Pixelrick420/Election.git
cd Electionsudo apt update
sudo apt install python3 python3-pip python3-venv python3-tk python3-dev build-essential# Create isolated virtual environment
python3 -m venv venv
source venv/bin/activate
# Upgrade package installer
pip install --upgrade pip# Core requirements
pip install Pillow>=9.0.0
# Optional: PDF generation capability
pip install reportlab>=3.6.0
# Optional: Enhanced image processing
pip install Pillow[imagingft]mkdir -p symbols results
chmod 755 symbols results# If using automated setup
cd Election
source venv/bin/activate
python3 run.py
# Alternative: Use desktop shortcut (if created during setup)- Launch application and observe Elections panel on left side
- Click Add button to create new election
- Enter descriptive election name (e.g., "Student Council President 2025")
- Configure strong admin password (minimum 8 characters recommended)
- Confirm creation and observe election appears in list
- Select election from list (authentication required)
- Enter admin password when prompted
- Navigate to Candidates section in right panel
- Click Add Candidate button
- Enter candidate full name
- Browse for symbol image (optional but recommended)
- Confirm addition and repeat for all candidates
- Verify all candidates added correctly
- Click Start button to enter voting mode
- System transitions to full-screen kiosk interface
- Voters interact with candidate selection buttons
- Vote casting requires Enter key confirmation
- Next ballot accessed via Space key
- End voting session using Ctrl+Q key combination
- Provide admin password authentication
- System automatically exports results in all formats
- Access View button for real-time results display
- Use Export button for manual export to custom directory
election_app/
├── __init__.py # Package initialization and version info
├── db.py # SQLite database management with connection pooling
├── main.py # Primary UI components and application logic
├── voting.py # Full-screen voting interface with security features
├── dialogs.py # Modal dialog components (Election, Candidate)
├── security.py # Cryptographic functions and password management
└── exporter.py # Multi-format results export functionality
- Purpose: Thread-safe SQLite database operations with connection management
- Features: Automatic schema migration, foreign key constraint enforcement, connection pooling
- Threading: Implements locking mechanism for concurrent access safety
- Purpose: Main application window providing election and candidate management
- Framework: Tkinter with enhanced styling and responsive layout design
- Features: CRUD operations, password authentication, results visualization
- Purpose: Secure full-screen voting experience with kiosk mode functionality
- Security: System key disabling, admin password exit requirement, process isolation
- Accessibility: Large buttons, audio feedback, keyboard navigation support
- Purpose: Multi-format report generation with error handling and fallback mechanisms
- Formats: JSON (structured data), CSV (spreadsheet compatibility), PDF (professional reports)
- Features: Automatic timestamping, symbol embedding, graceful degradation
Elections require unique names and admin passwords. The system generates SHA-256 password hashes for security.
# Database structure for elections
Elections: {
id: INTEGER PRIMARY KEY,
name: TEXT UNIQUE,
admin_password_hash: TEXT,
created_at: TIMESTAMP
}- Name Requirements: Unicode support, no length restrictions
- Symbol Management: Optional image files with automatic scaling
- Storage Method: File path references with existence validation
- Full-screen Mode:
attributes('-fullscreen', True)with topmost priority - System Key Blocking: X11 xmodmap commands disable Super/Windows keys
- Process Protection: Window close events intercepted and blocked
- Emergency Exit: Ctrl+Q combination requires admin password verification
- Candidate Selection: Visual feedback with color state changes (red → green)
- Vote Casting: Enter key triggers database insertion with timestamp
- Confirmation Display: "BALLOT CAST" screen with visual checkmark
- Next Ballot: Space key resets interface for subsequent voter
Multi-tier audio implementation for maximum compatibility:
Priority 1: WAV generation + aplay (Ubuntu optimized)
Priority 2: PulseAudio bell sample
Priority 3: Terminal bell character fallbackINSERT INTO Votes (election_id, candidate_id, timestamp)
VALUES (?, ?, CURRENT_TIMESTAMP)SELECT c.name, COUNT(v.id) as votes,
(COUNT(v.id) * 100.0 / ?) as percentage
FROM Candidates c
LEFT JOIN Votes v ON c.id = v.candidate_id
WHERE c.election_id = ?
GROUP BY c.id, c.name
ORDER BY votes DESC| Column | Type | Constraints | Description |
|---|---|---|---|
id |
INTEGER | PRIMARY KEY AUTOINCREMENT | Unique election identifier |
name |
TEXT | NOT NULL UNIQUE | Human-readable election name |
admin_password_hash |
TEXT | NOT NULL | SHA-256 hashed admin password |
created_at |
TIMESTAMP | DEFAULT CURRENT_TIMESTAMP | Election creation timestamp |
| Column | Type | Constraints | Description |
|---|---|---|---|
id |
INTEGER | PRIMARY KEY AUTOINCREMENT | Unique candidate identifier |
election_id |
INTEGER | NOT NULL, FOREIGN KEY | Reference to parent election |
name |
TEXT | NOT NULL | Candidate display name |
symbol_path |
TEXT | NULLABLE | File system path to symbol image |
is_nota |
INTEGER | DEFAULT 0 | NOTA flag (1 for auto-generated NOTA) |
| Column | Type | Constraints | Description |
|---|---|---|---|
id |
INTEGER | PRIMARY KEY AUTOINCREMENT | Unique vote identifier |
election_id |
INTEGER | NOT NULL, FOREIGN KEY | Reference to election |
candidate_id |
INTEGER | NOT NULL, FOREIGN KEY | Reference to selected candidate |
timestamp |
TIMESTAMP | DEFAULT CURRENT_TIMESTAMP | Vote casting timestamp |
- CASCADE DELETE: Election deletion removes all associated candidates and votes
- FOREIGN KEY ENFORCEMENT:
PRAGMA foreign_keys = ONenforced at connection level - Transaction Safety: All operations wrapped in database transactions
- Hash Algorithm: SHA-256 with UTF-8 encoding
- Storage Policy: Plain text passwords never stored or logged
- Verification: Constant-time comparison prevents timing attacks
- Kiosk Mode Implementation: Full-screen window with system integration blocking
- Key Interception: X11 key mapping modification during voting sessions
- Process Isolation: Window manager integration prevention
- Admin Override: Secure exit mechanism with password verification
- Database Isolation: SQLite file-based storage with local access only
- Input Sanitization: All user inputs validated and escaped
- File System Security: Controlled access to symbol and export directories
{
"election_name": "Student Council Election",
"total_votes": 247,
"timestamp": "20250809_143022",
"results": [
{
"candidate": "Alice Johnson",
"votes": 123,
"percentage": 49.80,
"symbol_path": "/path/to/symbols/alice.png"
},
{
"candidate": "Bob Williams",
"votes": 89,
"percentage": 36.03,
"symbol_path": "/path/to/symbols/bob.png"
},
{
"candidate": "NOTA",
"votes": 35,
"percentage": 14.17,
"symbol_path": null
}
]
}Standard comma-separated values with UTF-8 encoding:
Candidate,Votes,Percentage
Alice Johnson,123,49.80
Bob Williams,89,36.03
NOTA,35,14.17
- Professional Layout: A4 page format with proper margins and spacing
- Corporate Styling: Dark blue headers, alternating row backgrounds
- Symbol Integration: Embedded candidate symbols with automatic scaling
- Metadata Inclusion: Election name, generation timestamp, vote totals
- Table Formatting: Structured presentation with ranking and statistics
All exports follow standardized naming:
{ElectionName}_{YYYYMMDD_HHMMSS}.{extension}
Examples:
Student_Council_2025_20250809_143022.jsonClass_President_20250809_143022.csvGrade_Representative_20250809_143022.pdf
Election/
├── setup.sh # Automated installation script
├── run.py # Application entry point
├── election_app/ # Main application package
│ ├── __init__.py # Package initialization
│ ├── db.py # Database management
│ ├── main.py # UI and application logic
│ ├── voting.py # Voting interface
│ ├── dialogs.py # Dialog components
│ ├── security.py # Security functions
│ └── exporter.py # Export functionality
├── symbols/ # Candidate symbol storage
├── results/ # Export output directory
├── venv/ # Python virtual environment
├── election.db # SQLite database (auto-created)
├── requirements.txt # Python dependencies
└── README.md # Documentation
# Optional: Custom database location
export ELECTION_DB_PATH="/custom/path/election.db"
# Optional: Custom symbols directory
export SYMBOLS_DIR="/custom/symbols/path"
# Optional: Custom results export directory
export RESULTS_DIR="/custom/results/path"
# Debug mode activation
export ELECTION_DEBUG=1The application implements a three-tier audio feedback system:
- Primary Backend: WAV file generation with ALSA playback
- Secondary Backend: PulseAudio bell sample playback
- Fallback Backend: ASCII bell character output
Audio dependencies (Ubuntu):
sudo apt install alsa-utils pulseaudio-utils
- Main window with elections list and candidate management panels
- Election creation dialog with name and password fields
- Candidate add/edit dialog with symbol selection
- Full-screen voting interface with candidate selection buttons
- Vote confirmation screen with checkmark indicator
- Results viewing window with vote counts and percentages (it does not allow taking screenshots. I have made it pretty secure, however it is far from fullproof)
{
"election_name": "GVHSS Panamaram 9D",
"total_votes": 7,
"timestamp": "20250809_231546",
"results": [
{
"candidate": "Rahul",
"votes": 2,
"percentage": 28.57,
"symbol_path": "/media/harikrishnanr/storage/Code/Election/symbols/pencil.png"
},
{
"candidate": "Adil",
"votes": 2,
"percentage": 28.57,
"symbol_path": "/media/harikrishnanr/storage/Code/Election/symbols/umbrella.png"
},
{
"candidate": "Alex",
"votes": 2,
"percentage": 28.57,
"symbol_path": "/media/harikrishnanr/storage/Code/Election/symbols/fan.png"
},
{
"candidate": "NOTA",
"votes": 1,
"percentage": 14.29,
"symbol_path": null
}
]
}
- JSON structure in text editor showing hierarchical data
- PDF report sample with embedded symbols and professional formatting
Candidate,Votes,Percentage
Rahul,2,28.57
Adil,2,28.57
Alex,2,28.57
NOTA,1,14.29
- CSV export displayed in spreadsheet application
- Connection Pooling: Thread-safe connection management with timeout handling
- Schema Migration: Automatic database schema updates for backward compatibility
- Transaction Management: Atomic operations with rollback capability
- Foreign Key Enforcement: Referential integrity maintained at database level
- Tkinter Enhancement: Custom styling with modern color schemes and typography
- Layout Management: Responsive design using pack and grid geometry managers
- Event Handling: Comprehensive keyboard and mouse event processing
- Widget Customization: Custom button states and visual feedback systems
# Symbol processing workflow
1. Image file validation and format detection
2. RGBA conversion for transparency support
3. Proportional scaling with aspect ratio preservation
4. Canvas-based composition with centered positioning
5. ImageTk conversion for Tkinter compatibility- Password Hashing: SHA-256 with UTF-8 encoding
- Session Management: Admin authentication per election access
- System Integration: X11 key mapping manipulation for kiosk mode
- Process Protection: Window manager interaction prevention
- Creation: Unique name assignment with admin password configuration
- Access Control: Password verification required for election modification
- Candidate Management: Add, edit, delete operations with immediate UI updates
- Voting Execution: Secure kiosk mode with audio feedback
- Results Export: Multi-format report generation with timestamp tracking
- Data Cleanup: Optional vote clearing with confirmation prompts
- Supported Formats: PNG (recommended), JPG, JPEG, GIF, BMP
- Automatic Processing: Scaling, centering, and format conversion
- Storage Strategy: File path references with existence validation
- Display Optimization: Square canvas with transparency preservation
- Selection State: Single candidate selection with visual feedback
- Vote State: Confirmation required before database commitment
- Completion State: Success display with next ballot preparation
- Error Handling: Invalid operations blocked with user feedback
| Key Combination | Function | Access Level |
|---|---|---|
Enter |
Cast vote for selected candidate | Voter |
Space |
Advance to next ballot | Voting Officer |
Tab |
Delete most recent vote | Voting Officer |
Ctrl+Q |
Exit voting mode | Admin (password required) |
Escape |
Blocked (security measure) | None |
Alt+Tab |
Blocked (security measure) | None |
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"election_name": {"type": "string"},
"total_votes": {"type": "integer"},
"timestamp": {"type": "string", "pattern": "^[0-9]{8}_[0-9]{6}$"},
"results": {
"type": "array",
"items": {
"type": "object",
"properties": {
"candidate": {"type": "string"},
"votes": {"type": "integer"},
"percentage": {"type": "number"},
"symbol_path": {"type": ["string", "null"]}
}
}
}
}
}- Page Format: A4 (210 × 297 mm)
- Margins: 18mm on all sides
- Font Family: Helvetica (system font)
- Header: Election name with 24pt bold typography
- Table Layout: Rank, Name, Votes, Percentage, Symbol columns
- Symbol Display: 0.6" × 0.4" embedded images with scaling
- Encoding: UTF-8 with BOM for Excel compatibility
- Delimiter: Comma separation with quote escaping
- Headers: Standard column names for database import
- Numeric Format: Percentage values with 2 decimal precision
# Error: No module named 'PIL'
pip install Pillow
# Error: Microsoft Visual C++ required (Windows)
pip install --upgrade setuptools wheel
# Error: Failed building wheel for some-package
sudo apt install python3-dev build-essential# Database locked error
sudo chown $USER:$USER election.db
chmod 644 election.db
# Schema corruption
rm election.db # Database will be recreated on next launch# No audio feedback (Ubuntu)
sudo apt install alsa-utils pulseaudio-utils
# Test audio functionality
aplay /usr/share/sounds/alsa/Front_Left.wav
# PulseAudio service restart
systemctl --user restart pulseaudioIf the voting interface becomes unresponsive:
- Attempt normal exit:
Ctrl+Q→ enter admin password - Switch to TTY:
Ctrl+Alt+F2 - Kill process:
pkill -f election_app - Return to GUI:
Ctrl+Alt+F7 - Restart application if needed
# Manual key restoration if automatic restoration fails
xmodmap -e 'keycode 133=Super_L'
xmodmap -e 'keycode 134=Super_R'
xmodmap -e 'add mod4 = Super_L Super_R'- Scrolling: Automatic scrollbar activation for >6 candidates
- Memory Management: Lazy image loading for symbol processing
- Database Indexing: Optimized queries for vote counting operations
- Memory Usage: Typical consumption 50-100MB during normal operation
- CPU Usage: Minimal during idle, brief spikes during image processing
- Disk I/O: Periodic database writes, batch export operations
- Separation of Concerns: Clear module boundaries with single responsibilities
- Error Handling: Comprehensive exception management with user feedback
- Type Safety: Implicit typing with defensive programming practices
- Resource Management: Proper cleanup of database connections and GUI resources
# Manual testing checklist
1. Election creation with various name formats
2. Candidate addition with different image types
3. Voting session with multiple ballots
4. Results export in all formats
5. Password authentication edge cases
6. Database integrity after operations- Custom Export Formats: Extend
ResultsExporterclass - Authentication Methods: Replace
SecurityManagerimplementation - UI Themes: Modify color schemes in main UI components
- Audio Systems: Add platform-specific audio backends
git clone https://github.com/Pixelrick420/Election.git
cd Election
python3 -m venv dev_env
source dev_env/bin/activate
pip install -r requirements.txt- Style Guide: PEP 8 compliance with 88-character line limits
- Documentation: Docstrings for all public methods and classes
- Error Handling: Explicit exception handling with user-friendly messages
- Threading: Thread-safe database operations with proper locking
- Fork repository on GitHub
- Create feature branch with descriptive name
- Implement changes with appropriate testing
- Ensure code style compliance
- Submit pull request with detailed description
This software is free to use, share, and modify. No license restrictions apply. Users may distribute and modify the code for any purpose, including commercial applications.
GitHub Repository: https://github.com/Pixelrick420/Election
Installation Script: The setup.sh script provides automated installation for Ubuntu 22.04 systems. Download and execute for complete system setup including all dependencies and configuration.