DEV Community

Codes With Pankaj
Codes With Pankaj

Posted on

Building a Sudoku Game in Python with Tkinter

Sudoku is a popular number puzzle game that challenges players to fill a 9x9 grid with digits so that each column, each row, and each of the nine 3x3 subgrids contain all of the digits from 1 to 9. In this blog post, we'll walk through the process of creating a simple Sudoku game using Python and the Tkinter library.

Setting Up the Environment

Before diving into the code, make sure you have Python installed on your machine. Additionally, Tkinter, the standard GUI toolkit for Python, is required. You can install Tkinter using the following command:

pip install tk
Enter fullscreen mode Exit fullscreen mode

The SudokuGame Class

The core of our Sudoku game is encapsulated in a class named SudokuGame. This class manages the game logic and the Tkinter GUI. Let's break down some key aspects of the code:

Initialization and Board Generation

def __init__(self, master):
    # ...
    self.board = [[0]*9 for _ in range(9)]
    self.initialize_board()
    self.create_widgets()
Enter fullscreen mode Exit fullscreen mode

The __init__ method initializes the game, creates the Tkinter window (master), and generates the initial Sudoku board using the initialize_board method.

Generating a Sudoku Board

def initialize_board(self):
    # ...
Enter fullscreen mode Exit fullscreen mode

The initialize_board method generates a completed Sudoku board and then removes some numbers to create the puzzle. It uses a random shuffling technique to create a unique board each time a new game starts.

Creating Tkinter Widgets

def create_widgets(self):
    # ...
Enter fullscreen mode Exit fullscreen mode

The create_widgets method sets up the Tkinter GUI. It creates an Entry widget for each cell in the Sudoku grid, allowing users to input their guesses directly. The "New Game" button triggers the new_game method to reset the game.

Handling User Input

def button_click(self, row, col):
    # ...
Enter fullscreen mode Exit fullscreen mode

The button_click method is called when a user clicks on a cell. If the cell is empty, the user can enter a number. The input is validated, and if it's a valid move, the board is updated. The check_win method is called to check if the puzzle is complete.

Checking for a Win

def check_win(self):
    # ...
Enter fullscreen mode Exit fullscreen mode

The check_win method verifies if the current board configuration satisfies the Sudoku rules, confirming whether the puzzle is solved. If true, a congratulations message is displayed.

Running the Application

if __name__ == "__main__":
    root = tk.Tk()
    app = SudokuGame(root)
    root.mainloop()
Enter fullscreen mode Exit fullscreen mode

The final block of code initializes the Tkinter root window and starts the main event loop to run the application.

Download Code

Read Blog

Top comments (0)