Python

# Sudoku Solver With GUI in Python

Sudoku solver in Python is a beginner-level exercise or project for college students. Writing a code for Sudoku solver using Python language makes it easier and simpler.

Sudoku is a logical puzzle grid game in which players insert numbers from one to nine in a grid with nine squares divided into nine smaller squares, so that each number appears once in a horizontal line, vertical line, and a square. This game is quite popular among mathematics lovers. Usually, sudoku is printed in daily newspapers, and the solution is published on the next day.

This article deals with writing code in Python to solve the sudoku puzzle using the recursion method. First, we will do the GUI part and then, proceed to solve the puzzle.

## Creating a GUI Sudoku Solver Using the Python Language

We will be creating GUI sudoku solver using the Jetbrains Pycharm IDE. Since we are creating an impressive sudoku solution with GUI, we will import the Tkinter library. Let’s start:

## Importing Library and Writing the Code

Import everything from Tkinter and create an instance for the Tkinter’s window. Set the title of the window as “Sudoku Solver”. Now, set the dimensions of the window using the Geometry method. We are taking the dimensions of the windows as 324×550 pixels.

Create a label that will indicate the usage of the program. Place the label on the 0th row and the first column using the Grid method. The set span of the column to 10 centers the label in the window.

Now, create another label that comes into play if the sudoku puzzle cannot be solved and initialize it with an empty string. The foreground color for the error label will be red in our case. Use the Grid method to place the label in the 15th row and 1st column, column span to 10, and padding to 5.

Create a label for the success of the sudoku solver. You can copy the code for the previous label and change the foreground color to green, and name the label as solved.

Let’s create an empty dictionary to store each cell of the input grid. Define a validation function to control the input in the cells. It will take the value of the cell as an argument.

### The Code Block: ## Write the Validation Function

Write the code to check the value if it is a digit or an empty string that allows users to delete the value. To restrict the input to only single-digit use and check if the value is lesser than 2, return the value of the Boolean expression.

### The Code Block: ## Registering the Function and Writing Another Function to Divide the Sudoku Into 3×3 Grids

Register the function to the window using the roots register method. Divide the sudoku 9×9 grid into smaller chunks of 3×3 by writing a function. This will take the row no., column no., and background colors as an argument.

Use a for loop with a range of three which will indicate the rows. Use another for loop inside it to indicate the columns. Now, create an entry widget with a width of 5, bg as bg color, and the center aligns the text using Justify. Also, validate the key to validate function upon the keypress.

Validate the command to a tuple of registered function and %P substitution code, which will pass the new value to function upon change. Place the widget at the sum of Row number as i+1 row and the sum of column number as j+1. You can set stick to new, which will make it sticky from all directions. Set padx and pady to 1 and internal padding to 5.

Now, store the entry widget in the dictionary with a tuple of row and column numbers that we used to place the widget as a key.

### The Code Block:  ## Write a Function to Draw a 9×9 Grid

We will write a function to create a 9×9 grid. I have used a two-color combo for this grid. The first color signifies the value. Use a for loop in range 1, 10 and step size as 3 for row no. Use another for loop inside with Range 0, 9 with step size 3.

Now, call the 3×3 function and pass row no., column no., and color. To alternate between the colors, make use of the if condition. If the value of the color variable is the first color, we will set it to the second color. Else we will set it to the first color. While writing the color codes, maintain the case of letters.

### The Code Block: ## Write a Function to Clear the Sudoku

We will write a clear values function for sudoku, which will clear the values in each grid cell. First, clear the errors and success labels, Again, iterate through the rows and columns. The range for the row would be 2, 11, and the range for columns will be 1, 10.

Call the entry widget we stored in a dictionary at a given row and column. Use the delete method of the entry widget to delete its value from index 0 to the end.

### The Code Block: ## Write a Function to Get Input From the User

Write the get values function and declare an empty list to store the values for each cell for each row. Again, clear all the labels to clear the text, if any. Use the for loop to iterate over the range 2, 11 for the rows and 1, 10 for columns. Now, get the value of cells using the entry widgets get method. If the value is the empty string, we will append a 0 to the rows list. Else append an integer value to the list.

After the end of the loop, append the rows list to the board list.

### The Code Block: ## Writing Code for Buttons

Using the button widget, create a button. Set the command to get the values, text to solve, and width to 10. Now, place the button on the 20th row and first column with a column span of 5 pady as 20.

Create another button by copying the same code, set its command to clear values function, and text to clear. Place this button in the 5th column.

### The Code Block: ## Calling the Functions

Call the 9×9 grid functions and roots main loop method to launch the instance of our created window. ## Writing Code

We will first declare a variable that will hold the number of rows and columns. Write the question that will validate a given number for a given row or column. This will take sudoku, row number, column number, and number as arguments. To check if the same number exists in the same row, we will use a for loop in the range of 9. The for loop condition goes like this: if the number of the given row and ith column is equal to num, we will return false.

Similarly, we will check if the same number exists in the same column. Use a for loop in the range of 9. If the number of the given column and jth row is equal to num, we will return false.

Now, we have to check if the same number exists in its particular 3×3 grid. The starting row will be row subtracted from row modulus 3. The starting column would be a column subtracted from column modulus 3.

Use two nested loops in a range of three. If the number at the start row plus ith row and start column plus jth column equal to num, we will return False. At the end of the function, we will return True, which will be executed if none of the previous conditions are satisfied.

### The Code Block: ## Write Function to Assign Values to Non-Assigned Locations

We will be writing a sudoku solver function to assign values to non-assigned positions. This will include sudoku matrix, starting row number, and starting column number as arguments.

Let us check if the row equals N-1 and the column equals n. If the condition prevails, we will return true. This condition will act as a base condition since we will be using recursion to solve the puzzle. After the last column is reached, we will move to the next column. If the column equals n, we will add one to the row and set the column back to zero. We will now check if a number is assigned to the current location

If the number at the given row and column is greater than zero, we will return solve sudoku function for the next column. Use a for loop in range 1, N+1 to check for each number from 1-9.

Now, we will check if it’s ok to assign this number to a given row and column using the function we wrote earlier. If it’s ok to assign the number, we will assign it in the sudoku. Let’s say the number assigned is correct. We will also check the possibility with the next column.

In the loops code block, we will reassign 0 since our assumption was wrong and it validates the next value. Return false at the end of the functions code block.

### The Code Block:  ## Write Function for Solved Sudoku

We will write a function that will return the solved sudoku if it’s solvable. This will take sudoku as an argument. To see if sudoku is solvable, use the if condition. We will return sudoku if it’s solvable. Else, we will return No.

Save this file as solver.py to the same folder where you saved your GUI file.

### The Code Block: ## Importing the Solver Function to GUI file

Open the GUI file and import the solver function from the solver.py file. Write update values function, which will update the cells and display the solution of sudoku. This will take the sudoku matrix as the argument.

Call the solver function and pass the sudoku to it. If the solution is not equal to NO, use a for loop in range 2, 11. Inside the for loop, use another for loop with a range of 1, 10. Delete the existing values from the cell. Use the insert method to insert the value at the 0th index.

The value will be the number at rows minus second row and column minus first column. We subtract 2 and 1, respectively, since the matrix is zero-indexed.

After the loop is set, the text of the solved label to sudoku is solved using the configure method. In the else part, we will set error labels text to no solution exists. ## Calling the Update Values

Call the get values function at the end and pass the board matrix.

As of now, our final program is ready for execution.

## Conclusion

You can create a sudoku solver using the recursion method as we have done here. But developing a sudoku solver with GUI puts more weight on your coding skills and makes it easier to solve the sudoku puzzles.

This post is divided into parts for the maintainability of the code. I hope you loved reading this article. Check the other Linux Hint articles for more tips and tutorials. 