Tic Tac Toe Python Code With GUI

Tic Tac Toe Python Code With GUI

Tic Tac Toe is a classic game that many people are familiar with. It is a two-player game where the players take turns marking their symbol (‘X’ or ‘O’) on a 3×3 grid. The first player to get three of their symbols in a row (either horizontally, vertically, or diagonally) wins the game. If all the cells are filled and no one has won, the game is a tie.

In this blog post, we will show you how to create a Tic Tac Toe game using Python and the Tkinter GUI library. Tkinter is a built-in library in Python and is one of the most popular GUI libraries for Python.

Let’s get started by creating a new Python file and importing the necessary libraries:

import tkinter as tk
from tkinter import messagebox

The tkinter library provides the core GUI functionality, while the messagebox module provides a simple way to display message boxes.

Next, we need to create a class to represent our Tic Tac Toe game. We’ll call this class TicTacToe. The __init__ method of this class will create the game board (a 3×3 grid of buttons) and initialize some variables to keep track of the current player and the state of the game:


class TicTacToe:
    def __init__(self, master):
        self.master = master
        self.master.title("Tic Tac Toe")

        # Initialize variables
        self.current_player = "X"
        self.board = [" "]*9

        # Create buttons for game board
        self.buttons = []
        for i in range(9):
            button = tk.Button(self.master, text=" ", font=("Helvetica", 20), width=5, height=2,
                               command=lambda index=i: self.play_turn(index))
            button.grid(row=i//3, column=i%3)

        # Create restart button
        restart_button = tk.Button(self.master, text="Restart", font=("Helvetica", 16), command=self.restart)
        restart_button.grid(row=3, column=1)


In this code, we first set the title of the window to “Tic Tac Toe”. We then create the game board by creating a list of 9 buttons, where each button is initially blank. We set the font, width, and height of the buttons and set their command to call the play_turn method with the button’s index as an argument.

We also create a restart button that calls the restart method when clicked.

Next, let’s implement the play_turn method. This method is called when a player clicks on a button on the game board. It checks if the button has already been clicked, and if not, it marks the button with the current player’s symbol (“X” or “O”) and updates the board list accordingly. It then checks if the game has been won or tied, and if so, displays a message box with the result:


    def play_turn(self, index):
        if self.board[index] == " ":
            self.board[index] = self.current_player

            if self.check_win():
                messagebox.showinfo("Game Over", f"{self.current_player} wins!")
            elif self.check_tie():
                messagebox.showinfo("Game Over", "Tie!")
                self.current_player = "O" if self.current_player == "X" else "X"

In this code, we first check if the button has already been clicked by checking if the corresponding element in the board list is not blank.

How To Run The Project?

To run the Tic Tac Toe game project that we have created, follow these steps:

  1. Open your preferred Python IDE (Integrated Development Environment) or text editor.
  2. Create a new Python file and name it something like tic_tac_toe.py.
  3. Copy and paste the entire code from our previous blog post into the new file.
  4. Save the file.
  5. Run the file by executing the command python tic_tac_toe.py in your terminal or by using the Run button in your IDE.

This will launch the game window, where you can play Tic Tac Toe by clicking on the buttons on the game board. You can restart the game by clicking on the “Restart” button.

That’s it! You now have a working Tic Tac Toe game built with Python and Tkinter. You can customize the game further by adding features like a scoreboard or different themes for the game board.


Leave a Comment

Verified by MonsterInsights