sudoko solver in python using GUI

introduction
Sudoku, a classic combinatorial number-placement puzzle, offers an engaging challenge that blends logic, pattern recognition, and patience. Its rules are simple—fill a 9×9 grid so that each row, column, and 3×3 subgrid contains all the digits from 1 to 9—but solving it can be highly non-trivial. Developing a Sudoku solver is a meaningful project that tests not only algorithmic logic but also user interface design when implemented with a GUI.
In this project, we build an interactive Sudoku Solver in python application using Python’s Tkinter GUI toolkit. It provides users with a clean 9×9 grid interface where they can manually enter puzzle values. Behind the scenes, the program uses a recursive backtracking algorithm—a depth-first search approach—to efficiently try possible values and backtrack when conflicts arise, eventually reaching a valid solution if one exists.
To make the app visually intuitive, each 3×3 subgrid is shaded alternately to mimic the appearance of paper Sudoku sheets. The program includes a step-by-step solving mode that visually demonstrates how the solver progresses cell-by-cell. This visualization is particularly helpful for learners seeking to understand how backtracking works in real-time.
Input validation is also integrated to ensure that users do not accidentally enter invalid numbers or characters. If any improper value is detected, the specific cell is highlighted, and the user is alerted via a message box. Additionally, users can clear the board entirely with one click and input a new puzzle at any time.
This project serves as a practical demonstration of:
Recursive algorithm design (backtracking)
Real-time UI updates with Tkinter
Input validation and error handling
Interactive application design and layout
steps to create sudoko solver in python
Step 1: Set Up Your Environment
Ensure Python is installed on your system.
You don’t need to install any external libraries—only the built-in
tkinter
andtime
modules are used.You can run the project in a Python file (
.py
) or in a Jupyter Notebook with GUI support.
Step 2: Import Required Modules
import tkinter as tk
from tkinter import messagebox
import time
tkinter
is used for building the GUI.messagebox
is used to display error or success messages.time
is used to add delay in step-by-step solving.
Step 3: Create the Main Application Window
Initialize a Tkinter window using
Tk()
.Set its title, dimensions, and background color.
Create a 9×9 grid of
Entry
widgets for user input.Alternate the background color of cells to differentiate 3×3 blocks.
Step 4: Create a Grid Data Structure
Store the
Entry
widgets in a 2D list for easy access.This grid allows reading and writing values to the puzzle cells.
Step 5: Add a Function to Retrieve Grid Input
Define a function
get_grid()
that:Loops through each entry field.
Converts valid numbers to integers.
Flags invalid or empty inputs and alerts the user.
Step 6: Implement the Backtracking Algorithm
Define two functions:
is_valid()
checks whether a number can be placed in a specific row, column, and 3×3 box.solve_board()
uses recursion to try numbers from 1 to 9 in each empty cell.
Add an optional animation mode using
time.sleep()
and GUI update calls to show step-by-step solving.
Step 7: Create a Function to Display the Solved Board
Once solved, populate each cell in the GUI with the correct number.
Reset the background color of each cell.
Step 8: Add Buttons for User Interaction
Add the following buttons below the Sudoku grid:
Solve Instantly: Solves the puzzle without delay.
Solve Step-by-Step: Shows solving visually with animation.
Clear: Clears all entries to allow new input.
Step 9: Bind Button Functions
Each button calls its respective function (
solve()
,clear()
).The solve function calls the solver and handles invalid or unsolvable puzzles.
Step 10: Run the Tkinter Main Loop
Use
root.mainloop()
to start the GUI event loop.This keeps the window responsive and handles all user interactions.
code explanation
1.Import Modules
The code starts by importing necessary modules:
tkinter
for creating the GUI,messagebox
for displaying alerts to the user,time
for adding delays in animated solving.
import tkinter as tk
from tkinter import messagebox
import time
2.Create Main Window and Grid
A Tk
window is created and titled. A 9×9 grid of Entry
widgets is initialized using a nested loop. These widgets are stored in a 2D list for easy reference. Each cell is assigned a background color to visually group 3×3 subgrids.
entries = [[None for _ in range(9)] for _ in range(9)]
3.Color Function
The function get_bg_color(i, j)
returns alternating colors based on the position in the 3×3 block for better visual clarity of the grid.
4.Get Grid Function
get_grid()
reads the current values from all entry widgets. If a cell is empty, it records zero. If an invalid character is entered, it highlights the cell and shows an error message.
5.Validity Check
The is_valid()
function checks whether placing a number at a given row and column violates Sudoku rules (no duplicates in row, column, or 3×3 box).
6.Backtracking Solver
solve_board()
is a recursive function implementing backtracking:
It searches for an empty cell.
Tries numbers 1 through 9.
If a valid number is found, it is placed and the function is called recursively.
If the puzzle reaches a dead end, it backtracks by resetting the cell to zero.
Optionally, visual updates and delays show the solving process step-by-step.
7.Display Solution
display_solution()
updates the GUI cells with the final solved values and resets their background to original.
8.Solve Function
solve()
collects the input grid, runs the solver, and updates the GUI with the solution. If the puzzle is invalid or unsolvable, it shows an error popup.
9.Clear Function
clear()
resets the entire grid by deleting all cell entries and restoring their original background colors.
10.Buttons and Layout
Three buttons are added:
“Solve Instantly”: solves without delay,
“Solve Step-by-Step”: enables solving with visual effect,
“Clear”: resets the grid.
These buttons are arranged below the Sudoku grid.
11.Start GUI
root.mainloop()
is called to start the Tkinter event loop, keeping the GUI window active and responsive to user interactions.
source code
import tkinter as tk
from tkinter import messagebox
import time
root = tk.Tk()
root.title(" Sudoku Solver")
root.geometry("430x500")
root.configure(bg="white")
entries = [[None for _ in range(9)] for _ in range(9)]
# Function to determine background color based on 3x3 block
def get_bg_color(i, j):
if (i // 3 + j // 3) % 2 == 0:
return "#e3f2fd" # light blue
else:
return "#ffffff" # white
# Build the Sudoku grid
for i in range(9):
for j in range(9):
e = tk.Entry(root, width=2, font=('Arial', 18), justify='center', bd=1, relief="solid",
bg=get_bg_color(i, j))
e.grid(row=i, column=j, padx=2, pady=2)
entries[i][j] = e
# Extract the grid from user input
def get_grid():
grid = []
for i in range(9):
row = []
for j in range(9):
val = entries[i][j].get()
if val == '':
row.append(0)
elif val.isdigit() and 1 <= int(val) <= 9:
row.append(int(val))
else:
entries[i][j].config(bg='salmon')
messagebox.showerror("Invalid Input", f"Invalid entry at row {i+1}, column {j+1}")
return None
grid.append(row)
return grid
# check if placing a number is valid
def is_valid(board, row, col, num):
for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
start_row, start_col = 3 * (row//3), 3 * (col//3)
for i in range(start_row, start_row+3):
for j in range(start_col, start_col+3):
if board[i][j] == num:
return False
return True
# Recursive backtracking solver (with optional animation)
def solve_board(board, step_by_step=False):
for i in range(9):
for j in range(9):
if board[i][j] == 0:
for num in range(1, 10):
if is_valid(board, i, j, num):
board[i][j] = num
if step_by_step:
entries[i][j].delete(0, tk.END)
entries[i][j].insert(0, str(num))
entries[i][j].config(bg="#c8e6c9") # greenish highlight
root.update()
time.sleep(0.05)
if solve_board(board, step_by_step):
return True
board[i][j] = 0
if step_by_step:
entries[i][j].delete(0, tk.END)
root.update()
time.sleep(0.05)
return False
return True
# ️ Display solution on grid
def display_solution(board):
for i in range(9):
for j in range(9):
entries[i][j].delete(0, tk.END)
entries[i][j].insert(0, str(board[i][j]))
entries[i][j].config(bg=get_bg_color(i, j))
# Solve the board
def solve(step_by_step=False):
board = get_grid()
if board:
if solve_board(board, step_by_step):
display_solution(board)
messagebox.showinfo("Solved", "Sudoku puzzle solved successfully!")
else:
messagebox.showerror("Unsolvable", "No solution exists for this puzzle.")
# Clear board
def clear():
for i in range(9):
for j in range(9):
entries[i][j].delete(0, tk.END)
entries[i][j].config(bg=get_bg_color(i, j))
# Buttons
btn_frame = tk.Frame(root, bg="white")
btn_frame.grid(row=9, column=0, columnspan=9, pady=20)
tk.Button(btn_frame, text="Solve Instantly", command=lambda: solve(False),
bg="#4CAF50", fg="white", font=('Arial', 12), padx=10).grid(row=0, column=0, padx=10)
tk.Button(btn_frame, text="Solve Step-by-Step", command=lambda: solve(True),
bg="#2196F3", fg="white", font=('Arial', 12), padx=10).grid(row=0, column=1, padx=10)
tk.Button(btn_frame, text="Clear", command=clear,
bg="#f44336", fg="white", font=('Arial', 12), padx=10).grid(row=0, column=2, padx=10)
root.mainloop()
output


